Center a layout in Android?
I have a linear layout, how can I add gravity to it so that it is horiz开发者_运维技巧ontally centred?
LinearLayout textHolder = new LinearLayout(context);
textHolder.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
The above does not appeat to work.
This should work
LinearLayout textHolder = new LinearLayout(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
lp.gravity = Graviity.CENTER_HORIZONTAL;
textHolder.setLayoutParams(lp);
But this will only center the children of the linearlayout according to textHolder's size. If you want to center the textHolder completely, the you should apply the layout params to the parent of textHolder.
精彩评论