How to Change Margin of TextView

前端 未结 8 1835
感动是毒
感动是毒 2020-12-04 13:11

I have TextView added Programmatically in to LinearLayout and on some external events I want to decrease bottom margin of that TextView to -10, for that I tried following. <

8条回答
  •  一向
    一向 (楼主)
    2020-12-04 13:57

    This one is tricky problem, i set margin to textview in a row of a table layout. see the below:

    TableLayout tl = new TableLayout(this);
    tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    
    TableRow tr = new TableRow(this);        
    tr.setBackgroundResource(R.color.rowColor);
    
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(4, 4, 4, 4);
    
    TextView tv = new TextView(this);
    tv.setBackgroundResource(R.color.textviewColor);
    tv.setText("hello");
    tr.addView(tv, params);
    
    TextView tv2 = new TextView(this);
    tv2.setBackgroundResource(R.color.textviewColor);
    tv2.setText("hi");
    tr.addView(tv2, params);
    
    tl.addView(tr);
    setContentView(tl);
    

    the class needed to import for LayoutParams for use in a table row is :

    import android.widget.**TableRow**.LayoutParams;
    

    important to note that i added the class for table row. similarly many other classes are available to use LayoutParams like:

    import android.widget.**RelativeLayout**.LayoutParams;
    

    import android.widget.LinearLayout.LayoutParams;

    so use accordingly.

提交回复
热议问题