How to set layout_gravity programmatically?

Adam Varhegyi picture Adam Varhegyi · Nov 8, 2011 · Viewed 291.5k times · Source

My question is simple,

How to set my buttons layout_gravity programmatically?

I found this on internet, but it simply throws me a Nullpointer exception:

 Button MyButton = new Button(this);

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


    MyLinearLayout.addView(MyButton);

Any solution?

Answer

Karthi picture Karthi · Nov 8, 2011

Java

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

button.setLayoutParams(params);

Kotlin

val params = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
    weight = 1.0f
    gravity = Gravity.TOP
}

For gravity values and how to set gravity check Gravity.

Basically, you should choose the LayoutParams depending on the parent. It can be RelativeLayout, LinearLayout etc...