50个Android开发技巧(01 好好利用layout_weight属性)

来源:互联网 发布:淘宝晚班客服兼职 编辑:程序博客网 时间:2024/06/11 01:58
问题:如何将一个Button放置在布局中间并将其宽度设为其parent的50%?
分析:问题想要达到的效果应该是这样:
(原文地址:http://blog.csdn.net/vector_yi/article/details/24397733)

这看起来不难,但很多开发者并不知道达到这样效果的最佳方法。

解决:在此我们将weightSum属性与layout_weight属性一起利用。
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:layout_width"fill_parent"  
  3.     android:layout_height"fill_parent"  
  4.     android:background"#ffffff"  
  5.     android:gravity"center"  
  6.     android:orientation"horizontal"  
  7.     android:weightSum"1" ><!--1.添加android:weightSum属性-->  
  8.   
  9.     <Button  
  10.         android:layout_width ="0dp"<!--2.将Button的layout_width设为0dp-->  
  11.         android:layout_height ="wrap_content"  
  12.         android:layout_weight ="0.5"<!--3.确保其占用了50%的可用空间-->  
  13.         android:text ="@string/activity_main_click_me" />  
  14.   
  15. </LinearLayout>  
可以注意到,在第2步将Button的layout_width设为了0dp,会不会与layout_weight有冲突?答案是不会:
  一个控件的宽度是这样计算出来的:
  Widget's width + Widget's weight*Parent's width/Parent's weightSum

0 0
原创粉丝点击