Android開發技巧(好好利用layout_weight屬性)
問題:如何將一個Button放置在布局中間并將其寬度設為其parent的50%?
</span>
這看起來不難,但很多開發者并不知道達到這樣效果的最佳方法。
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:background= "#ffffff" android:gravity= "center" android:orientation= "horizontal" android:weightSum= "1" ><!--1.添加android:weightSum屬性--> <Button android:layout_width ="0dp"<!--2.將Button的layout_width設為0dp--> android:layout_height ="wrap_content" android:layout_weight ="0.5"<!--3.確保其占用了50%的可用空間--> android:text ="@string/activity_main_click_me" /> </LinearLayout>
可以注意到,在第2步將Button的layout_width設為了0dp,會不會與layout_weight有沖突?答案是不會:
一個控件的寬度是這樣計算出來的:
Widget's width + Widget's weight*Parent's width/Parent's weightSum
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!