问题描述
这个属性可以在Java代码中动态改变吗?
Can this attribute be changed dynamically in Java code?
android:layout_marginRight
我有一个 TextView
,它必须动态地将它的位置向左改变一些像素.
I have a TextView
, that has to change its position some pixels to the left dynamically.
如何以编程方式执行此操作?
How to do it programmatically?
推荐答案
一种更通用的方法,不依赖于布局类型(除了它是一种支持边距的布局类型):
A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):
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 中,请尝试以下操作:
You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:
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 以更改边距.
I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.
不要忘记,如果你的 TextView 在里面,例如,一个RelativeLayout,应该使用 RelativeLayout.LayoutParams 而不是LinearLayout.LayoutParams
这篇关于以编程方式更改视图的右边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!