我的问题很简单,

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

// 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;
    }

其他回答

MyButton.setGravity(Gravity.RIGHT);

对于layout_gravity使用“karthi”给出的答案。这个方法设置重力以将子视图放置在视图中。

到RelativeLayout,试试这段代码,它为我工作: yourLayoutParams.addRule (RelativeLayout.ALIGN_PARENT_RIGHT);

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等等…

试试这段代码

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

or

    btn.setGravity(Gravity.TOP);

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

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

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

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