I'd hate to be resurrecting old threads but this is a problem that is not answered correctly and moreover I've run 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
work 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 MATCH_PARENT (think of it as auto margin). layout_gravity centre WILL affect view that is MATCH_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(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
button.setLayoutParams(params);
Link to LinearLayout.LayoutParams
.
android:layout_gravity
shows "No related methods" meaning cannot be accessed programatically.
Whereas gravity is a field in the class.