Search code examples
androidandroid-linearlayouttextviewandroid-layoutparams

android correct padding between views programmatically


I programmatically created four Textviews and added it in my Linearlayout.my linearlayout has 216dp width and TextView which I created pro-grammatically has 48 dp width and height. I want to add padding between TextView. I wrote some code but I received this result

as you can see padding is not correct,because in right side is incorrect

this is a my code

 for (int i = 0; i < mDigits; i++) {
        DigitView digitView = new DigitView(getContext());

        digitView.setWidth(valueInPixels);//48dp
        digitView.setHeight(valueInPixels);//48dp
        digitView.setTextColor(Color.WHITE);
        digitView.setTextSize(mDigitTextSize);
        digitView.setGravity(Gravity.CENTER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            digitView.setElevation(mDigitElevation);
        }

        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        if (i > 0) {
            lp.leftMargin = 10;//problem is this line
        }
        childView.addView(digitView, lp);//childview 216dp
    }

how i can to create correct padding between views programmatically? if anyone has solution please help me thanks.


Solution

  • First add appropriate android:paddingLeft to your childview I added as below:

    <LinearLayout
            android:id="@+id/childView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:background="#000"
            android:orientation="horizontal">
    

    Then edit you code as below

    for (int i = 0; i < 4; i++) {
                DigitView digitView = new DigitView(this);
    
                digitView.setWidth(valueInPixels);//48dp
                digitView.setHeight(valueInPixels);//48dp
                digitView.setTextColor(Color.WHITE);
                digitView.setBackgroundColor(Color.YELLOW);
                digitView.setTextSize(mDigitTextSize);
                digitView.setGravity(Gravity.CENTER);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    digitView.setElevation(mDigitElevation);
                }
    
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                lp.rightMargin = 10;//problem is this line
    
                childView.addView(digitView, lp);//childview 216dp
            }