How to set layout_gravity programmatically?

I'd hate to be resurrecting old threads but this is a problem that is not answered correctly and moreover I've ran into this problem myself.

Here's the long bit, if you're only interested in the answer please scroll all the way down to the code:

android:gravity and android:layout_gravity works differently. Here's an article I've read that helped me.

GIST of article: gravity affects view after height/width is assigned. So gravity centre will not affect a view that is done FILL_PARENT (think of it as auto margin). layout_gravity centre WILL affect view that is FILL_PARENT (think of it as auto pad).

Basically, android:layout_gravity CANNOT be access programmatically, only android:gravity. In the OP's case and my case, the accepted answer does not place the button vertically centre.

To improve on Karthi's answer:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
button.setLayoutParams(params);

Link to LinearLayout.LayoutParams.

android:layout_gravity shows "No related methods" meaning cannot be access programatically. Whereas gravity is a field in the class.


MyButton.setGravity(Gravity.RIGHT);

For layout_gravity use the answer stated by "karthi". This method sets gravity to place the children inside the view.


I had a similar problem with programmatically setting layout_gravity on buttons in a GridLayout.

The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored.

grid.addView(button)
((GridLayout.LayoutParams)button.getLayoutParams()).setGravity(int)

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...