我的问题很简单,

如何设置我的按钮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。

其他回答

这个问题很老了,但我遇到过同样的问题,并像这样解决了它

LayoutParams lay = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)
lay.gravity = Gravity.CENTER;

如果你想改变现有视图的layou_gravity,可以这样做:

((FrameLayout.LayoutParams) view.getLayoutParams()).gravity = Gravity.BOTTOM;

记住要根据视图所在的布局类型使用正确的LayoutParams。例:

LinearLayout.LayoutParams

如果你需要为视图设置重力,请使用以下方法

Button b=new Button(Context);
b.setGravity(Gravity.CENTER);

用于设置按钮的layout_gravity 为布局参数使用重力场

LayoutParams lp=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER;

试试这个 希望天气晴朗 谢谢

我从LinearLayout切换过来。LayoutParams to RelativeLayout。LayoutParams来最终得到我在创建的自定义圆环视图上想要的结果。

但是你用的不是gravity而是addRule

RelativeLayout。mCircleParams = new RelativeLayout.LayoutParams(circleheight,circleheight);

    mCircleParams.addRule(RelativeLayout.CENTER_IN_PARENT);

我使用类似这样的东西:(Xamarin和c#代码)

  LinearLayout linLayout= new LinearLayout(this); 
    linLayout.SetGravity(GravityFlags.Center);

    TextView txtView= new TextView(this);  
     linLayout.AddView(txtView); 

SetGravity把我的textView放在布局的中心。 SetGravity layout属性引用布局内容