如何用android:layout_weight弄个满意的比例

在布局中android:layout_width 和 android:layout_height 一般会设为wrap_content和match_parent,当再设置android:layout_weight的时候,有时候就会出现混乱

例如:

两个TextView的都为 android:layout_width = “match_parent”
“One, One”TextView的android:layout_weight = “1”
“One, Two”TextView的android:layout_weight = “2”

预测结果:

“One, One”TextView占屏幕宽的1/3
“One, Two”TextView占屏幕宽的2/3

代码:

        <LinearLayout            android:orientation="horizontal"            android:layout_width="match_parent"            android:layout_height="match_parent">            <TextView                android:text="One,One"                android:layout_width="match_parent"                android:layout_height="match_parent"                android:layout_weight="1"                android:id="@+id/textView11"                android:background="@drawable/textview_border"                android:textColor="@android:color/white"                android:layout_marginLeft="3dp"                android:layout_marginRight="3dp"                android:gravity="center"                 />            <TextView                android:text="One,Two"                android:layout_width="match_parent"                android:layout_height="match_parent"                android:layout_weight="2"                android:id="@+id/textView12"                android:background="@drawable/textview_border"                android:textColor="@android:color/white"                android:layout_marginLeft="3dp"                android:layout_marginRight="3dp"                android:gravity="center"              />        LinearLayout>

实际结果:

分析:

android:layout_weight = “1” 的 “One, One”TextView占屏幕的2/3
android:layout_weight = “2” 的 “One, Two”TextView占屏幕的1/3

原因:

android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!

解释:

设屏幕宽度为L,在两个TextView的宽度都为match_parent的情况下,原有宽度为L,两个的TextView的宽度都为L,那么剩余宽度为L-(L+L) = -L
“One, One” TextView的weight设置占1/3,所以总宽度是L+(-L)*1/3 = (2/3)L.
“One, Two” TextView的weight设置占2/3,所以总宽度是L+(-L)*2/3 = (1/3)L.

  • Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!

更多相关文章

  1. android软键盘右下角按键设置
  2. 通过在xml布局文件中设置android:onClick=""来实现组件单击事件
  3. android 设置系统自带字体
  4. layout布局属性
  5. 提取一个带计数框的EditText
  6. Android(安卓)设置横屏模式显示
  7. android那些事——android的成长
  8. android 设置全屏方法2
  9. Android(安卓)选择控件

随机推荐

  1. Android IntentService 分析
  2. android之AlerDialog
  3. 【随记】Android GPS定位(编辑中)
  4. Android 中比较好的adapter的写法
  5. android 录音操作
  6. Android游戏引擎
  7. Android 封装SharedPreference工具类
  8. Hack Android SD Card support
  9. android仿优酷超炫菜单
  10. Android(安卓)ListView异步加载图片乱序