开发者

Center a layout in Android?

开发者 https://www.devze.com 2023-04-11 12:45 出处:网络
I have a linear layout, how can I add gravity to it so that it is horiz开发者_运维技巧ontally centred?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消