How to set margins for TextView programmatically?

2019-03-11 13:58发布

TextView tv1 = new TextView(this);      
tv1.setPadding(5, 0, 5, 0);
tv1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
tv1.setBackgroundColor(Color.parseColor("#0099cc"));
tv1.setTextColor(Color.WHITE);
tv1.setTextSize(11);
tv1.setGravity(Gravity.LEFT | Gravity.BOTTOM);
tv1.setText("Test1");
ll.addView(tv1);

TextView tv2 = new TextView(this);      
tv2.setPadding(5, 0, 5, 0);
tv2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
tv2.setBackgroundColor(Color.parseColor("#0099cc"));
tv2.setTextColor(Color.WHITE);
tv2.setTextSize(11);
tv2.setGravity(Gravity.LEFT | Gravity.BOTTOM);
tv2.setText("Test2");
ll.addView(tv2);

As you can see, in this peace of code I set TextView's background color. What I want to do is I want to separate both of these TextView's from each other, so that their background colors would be separated by a line. I don't want them to connect. As I understand, it would be possible to do so, if I could set margins of TextView, but as I know, TextView's are not able to do so.

3条回答
forever°为你锁心
2楼-- · 2019-03-11 14:38

This one should be tried

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        params.setMargins(10,20,30,20);
        txt_gender.setLayoutParams(params);
查看更多
爷、活的狠高调
3楼-- · 2019-03-11 14:51

It depends according to your parent view.

If you using LinearLayout on your textview parent view give params like below

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);

If you using RelativeLayout on your textview parent view give params like below

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.WRAP_CONTENT, RelativeLayout.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);
查看更多
劫难
4楼-- · 2019-03-11 15:04

set to LayoutParams.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
tv1.setLayoutParams(params);
查看更多
登录 后发表回答