我的问题很简单,

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

其他回答

如果你想把一个视图放在父母的中心,你可以用下面的代码。

public class myLayout extends LinearLayout {

    public myLayout(Context context) {
      super(context);

      RelativeLayout vi = (RelativeLayout) ((LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
            R.layout.activity_main, null);
      LinearLayout.LayoutParams cc = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      cc.gravity = Gravity.CENTER;
      this.setGravity(Gravity.CENTER);
      this.addView(vi);
  }
}

这些代码部分使得LinearLayout把第一个视图元素放在父元素的中心。 因此,我们的系统不考虑初始的宽度和高度来安排在中心的视图。 代码部分我做得很好。

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

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

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

LinearLayout.LayoutParams

试试这段代码

    Button btn = new Button(YourActivity.this);
    btn.setGravity(Gravity.CENTER | Gravity.TOP);
    btn.setText("some text");

or

    btn.setGravity(Gravity.TOP);

完美的工作! !以上答案都不适合我。在Xml文件中设置gravity和设置layout_gravity是不同的。检查下面的代码

// here messageLL is the linear layout in the xml file
// Before adding any view just remove all views
   messageLL.removeAllViews();
// FrameLayout is the parent for LinearLayout
FrameLayout.LayoutParams params = new 
   FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
   params.gravity = Gravity.CENTER|Gravity.CENTER_VERTICAL;
   messageLL.setLayoutParams(params);
   messageText.setVisibility(View.GONE);
   messageNoText.setVisibility(View.VISIBLE);
   messageLL.addView(messageNoText);

也检查这个,在那里你可以找到关于重力和layout_gravity的清楚解释。

KOTLIN在FrameLayout上设置多个重力而不改变大小:

     // assign more than one gravity,Using the operator "or"
    var gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL
     // update gravity
    (pagerContainer.layoutParams as FrameLayout.LayoutParams).gravity = gravity
     // refresh layout
     pagerContainer.requestLayout()