LinearLayout关于weight使用问题

来源:互联网 发布:淘宝购物怎样查询物流 编辑:程序博客网 时间:2024/05/16 18:59

今天在解决安卓应用兼容性问题,问题是由于使用LinearLayout的weight引起的,下面我使用一个Demo简述一下问题以及解决方法。

样例1:使用weight的是布局文件,包含TextView

<LinearLayout        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_weight="1"        android:background="@drawable/spinner_bg"        android:gravity="center" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:gravity="center"            android:text="测试1" />    </LinearLayout>
测试效果:小米A2以及红米Note HD两个手机的样式都一样,如下


样例2:使用weight的是布局文件,包含CheckBox,第一个替换

 <LinearLayout        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_weight="1"        android:background="@drawable/spinner_bg"        android:gravity="center" >        <CheckBox            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:button="@null"            android:gravity="center"            android:text="测试1" />    </LinearLayout>
测试效果:

小米A2测试效果:红米Note测试效果:

上面的测试结果来看小米A2的替换为CheckBox的第一个内容向右偏移了,红米Note正常。如果我们只针对布局参数来调整的话,调试不出来居中效果,但是如果你设置了CheckBox的背景就可以了,这个可以使 android:background="@android:color/transparent",设置之后就会居中对齐,不仅CheckBox有这个问题,Radiobutton也有这个问题,因为在项目里面正好都用到,而且出现 了相同的问题,不居中。整个代码如下:

<LinearLayout        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_weight="1"        android:background="@drawable/spinner_bg" >        <CheckBox            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:gravity="center"            android:background="@android:color/transparent"            android:button="@null"            android:text="测试1" />    </LinearLayout>
可能有人会说你直接用CheckBox就可以了,为什么还要加LinearLayout包一层,这个是由于项目效果问题,下面我截图演示一下,对于我的项目加和不加一层布局的区别,下面是项目用到的两个截图,这里我介绍一下左边标题是“精选推荐”的。


"精选推荐"是使用CheckBox+drawableRight来实现文字加下三角,看到UI,很多人会想到TextView+drawableRight,我这个项目的功能问题,我选择的是CheckBox+drawableRight来实现,如果看CheckBox源码的话,最后CheckBox也是TextView一个子类,接下来只使用CheckBox+drawableRight来作为item,

<CheckBox        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_weight="1"        android:background="@drawable/spinner_bg"        android:button="@null"        android:drawableRight="@drawable/tri_normal"        android:gravity="center"        android:text="测试1" />

显示效果如下:

,结果右边的小三角跑到最右边了,用户体验性不太好,也与项目UI不符合,所以加一个父布局,修改代码如下:

,这样的话就跟Spinner一样了,由于到兼容性以及项目用到的下拉有二级菜单,所以就没有使用Spinner来开发。


对于CheckBox以及RadioButton这一类的组件,如果父布局使用了weight后,需要设置其背景当然也可以设置透明,这样位置属性才能用。

2 0
原创粉丝点击