我的问题很简单,
如何设置我的按钮layout_gravity编程?
我在互联网上找到了这个,但它只是抛出了一个空指针异常:
Button MyButton = new Button(this);
LinearLayout.LayoutParams lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
lllp.gravity=Gravity.RIGHT;
MyButton.setLayoutParams(lllp);
MyLinearLayout.addView(MyButton);
有解决方案吗?
其余的答案都是对的,我想补充更多的解释。layout_gravity是关于如何在父视图中定位视图。
在调用方法parentView.addView() **后,必须设置重力**。我们可以看到代码:
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("Layout parameters cannot be null");
}
mLayoutParams = params;
resolveLayoutParams();
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();
}
空指针的问题是因为它在getLayoutParams()之前没有调用addView。
注释已经说过“如果这个视图没有附加到父视图组,或者{@link#setLayoutParams(android.view.ViewGroup.LayoutParams)}没有成功调用,这个方法可能会返回null。”当一个View附加到父ViewGroup时,这个方法不能返回null。
以上大部分答案都是对的,所以写了一个辅助方法,让你可以使用它
直接在你的项目中。
以编程方式设置layout_gravity
// gravity types : Gravity.BOTTOM, Gravity.START etc.
// view : can be any view example : button, textview, linearlayout, image etc.
// for single view
public static void setLayoutGravity(int gravity, View view){
((LinearLayout.LayoutParams) view.getLayoutParams()).gravity = gravity;
}
// for mulitple views
public static void setLayoutGravity(int gravity, View ...view){
for(View item : view)
((LinearLayout.LayoutParams) item.getLayoutParams()).gravity = gravity;
}
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
}
对于重力值和如何设置重力检查重力。
基本上,你应该根据父类选择LayoutParams。它可以是RelativeLayout, LinearLayout等等…