编辑:一种更通用的方法,不依赖于布局类型(除了它是支持边距的布局类型之外):
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 http://developer.android.com/reference/android/widget/TextView.html。基本上,您需要获取 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 来更改边距。
NOTE
不要忘记,如果您的 TextView 位于内部,例如相对布局,应该使用相对布局.LayoutParams代替
LinearLayout.LayoutParams