Android单个控件占父控件宽度一半且水平居中

前些天,在工作中遇到了一个需求:一个“加载上一页”的按钮宽度为父控件宽度一半,且水平居中于父控件中。

在此给出两种思路:

1.直接在Activity代码中获取到当前父控件的宽度,并将此按钮宽度值设置成父控件宽度的一半。

2.通过借用LinearLayout的 weightSum 和 layout_weight 属性达到效果。

具体代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="horizontal"
    android:weightSum="2" >

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#f00f"
        android:text="这是一个按钮" >
    </Button>

</LinearLayout>

http://www.cnblogs.com/lwbqqyumidi/archive/2013/12/17/3477708.html

posted @ 2016-05-18 15:49  H_bolin  阅读(843)  评论(0编辑  收藏  举报