如何以编程方式设置layout_gravity? [英] How to set layout_gravity programmatically?
本文介绍了如何以编程方式设置layout_gravity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题很简单
如何以编程方式设置我的按钮layout_gravity?
How to set my buttons layout_gravity programmatically?
我在互联网上找到了这个,但是它只是抛出了一个Nullpointer异常:
I found this on internet, but it simply throws me a Nullpointer exception:
Button MyButton = new Button(this);
LinearLayout.LayoutParams lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
lllp.gravity=Gravity.RIGHT;
MyButton.setLayoutParams(lllp);
MyLinearLayout.addView(MyButton);
有解决方案吗?
推荐答案
Java
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;
button.setLayoutParams(params);
科特琳
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
weight = 1.0f
gravity = Gravity.TOP
}
有关重力值以及如何设置重力的信息,请检查重力
For gravity values and how to set gravity check Gravity.
基本上,应该根据父级选择LayoutParams
.可以是RelativeLayout
,LinearLayout
等...
Basically, you should choose the LayoutParams
depending on the parent. It can be RelativeLayout
, LinearLayout
etc...
这篇关于如何以编程方式设置layout_gravity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文