我的问题很简单,

如何设置我的按钮layout_gravity编程?

我在互联网上找到了这个,但它只是抛出了一个空指针异常:

 Button MyButton = new Button(this);

    LinearLayout.LayoutParams  lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
    lllp.gravity=Gravity.RIGHT;
    MyButton.setLayoutParams(lllp); 


    MyLinearLayout.addView(MyButton);

有解决方案吗?


当前回答

完美的工作! !以上答案都不适合我。在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的清楚解释。

其他回答

MyButton.setGravity(Gravity.RIGHT);

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

修改现有的布局参数并重新设置布局参数

//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams

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

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

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

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

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

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

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