更改视图编程一个合适的保证金? [英] Change the Right Margin of a View Programmatically?
问题描述
可这个属性被动态Java中code变化?
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
Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams
这篇关于更改视图编程一个合适的保证金?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!