Android單個控件占父控件寬度一半且水平居中


前些天,在工作中遇到了一個需求:一個“加載上一頁”的按鈕寬度為父控件寬度一半,且水平居中於父控件中。

在此給出兩種思路:

1.直接在Activity代碼中獲取到當前父控件的寬度,並將此按鈕寬度值設置成父控件寬度的一半。

2.通過借用LinearLayout的 weightSum 和 layout_weight 屬性達到效果。

具體代碼如下:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2  android:layout_width="match_parent"
 3  android:layout_height="match_parent"
 4  android:gravity="center_horizontal"
 5  android:orientation="horizontal"
 6  android:weightSum="2" >
 7 
 8     <Button  9         android:layout_width="0dp"
10  android:layout_height="wrap_content"
11  android:layout_weight="1"
12  android:background="#f00f"
13  android:text="這是一個按鈕" >
14     </Button>
15 
16 </LinearLayout>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM