目录

问题:

通过文档,查到TextView下有这么个方法
setLayoutParams(ViewGroup.LayoutParams params)
但是ViewGroup.LayoutParams这个东西,并没有setMargins方法,LinearLayout.LayoutParams才有,这可咋办?

答案:

手册上这样讲public void setLayoutParams (ViewGroup.LayoutParams params), 『该方法提供一些参数给父视图,指定了该view在父视图中的位置(或者说布局)。』

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged.Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged.

如果需要动态改变TextView(或者其它View)的margin属性(android:layout_marginTop, android:layout_marginBottom, android:layout_marginLeft, android:layout_marginRight),最好是通过代码动态添加这个View,而不是在layout中定义该View。

如果父视图是LinearLayout,那么就可以直接调用textView.setLayoutParams(params),然后在添加textView到LinearLayout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layoutView);

int left, top, right, bottom;
left = top = right = bottom = 64;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);

TextView textView = new TextView(this);
textView.setText("A Label");
textView.setLayoutParams(params);

layout.addView(textView);

如果父视图是RelativeLayout 或者 FrameLayout,上面的做法无效,解决的办法是新建一个LinearLayout,然后把textView添加给它,再把这个LinearLayout添加给父视图:

FrameLayout layout = (FrameLayout) findViewById(R.id.layoutView);

int left, top, right, bottom;
left = top = right = bottom = 64;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);

TextView textView = new TextView(this);
textView.setText("A Label");
textView.setLayoutParams(params);

LinearLayout ll = new LinearLayout(this); // + 增加行
ll.setOrientation(LinearLayout.VERTICAL); // + 增加行
ll.addView(textView); // + 增加行

// layout.addView(textView); // - 删除行
layout.addView(ll); // + 增加行 

以上代码经过测试。

拓展阅读:

让android的TextView可以滚动