我正在从Activity动态创建TextView。我创建了2个Textviews,我想在两个TextView之间保持一些差距。如何通过代码而不是XML来实现。通常在XML中我们使用android:layout_marginLeft / Right标签来保持2个TextView之间的差距。如何通过代码实现这一目标?
提前致谢,
答案 0 :(得分:2)
这取决于您使用的布局。此示例将RelativeLayout放在LinearLayout
中LinearLayout linearLayoutParent;
RelativeLayout relativeLayout;
RelativeLayout.LayoutParams margin = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
margin.setMargins(0, 0, 0, 7); //7px bottom margin
//get or create the linear and the relative layouts
...
// Add view with its margins
linearLayoutParent.addView(relativeLayout, margin);
答案 1 :(得分:2)
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
layoutParams.setMargins(10, 10, 10, 10);
view.setLayoutParams(layoutParams);