编辑:一个更通用的方法,这样做不依赖于布局类型(除了它是支持边距的布局类型):
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
你应该检查文档的TextView.基本上,你会想要获得TextView的LayoutParams对象,并修改边距,然后将其设置回到TextView。假设它在一个LinearLayout,尝试这样:
TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);
我现在不能测试,所以我的铸造可能会关闭一点,但LayoutParams是需要修改以更改边距。
注意
Don’t forget that if your TextView is inside, for example, a
RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams