Android的LinearLayout水平一行使控件居右对齐
Android的LinearLayout水平一行使控件居右对齐
本文来源自极乐鸟博客 2014年7月31日
上海 天气热
有这样一个场景:Android的listview中每一行因为都要写个单独的针对这一行item的layout文件,而这一行数据的布局需求是这样的,一个图片,一个文字显示,一个checkbox复选框。其中图片大小是固定的,而每行的文本长度确实不一样的。
基于这样的一个布局需求,我们为其设计,必然左侧的图片都是要居左对齐的,其后的可变的文本,最后的checkbox复选框显然必须得居右对齐。
但就是在这样一个简单的页面布局上,我确花费了2小时之多的时间来完成,当然最后还是在网络资源的帮助下完成的。
具体思路是:
将最右边的的checkbox复选框控件单独放在另一个LinearLayout中,同时将其对齐方式设为右对齐:android:gravity="right",还有一点,这个LinearLayout的宽度设为充满父控件: android:layout_width="fill_parent"。
完整的XML代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="可变要显示的文字" /> <!-- 下面到关键部分: 将最右边的的checkbox复选框控件单独放在另一个LinearLayout中 同时将其对齐方式设为右对齐:android:gravity="right" 同时将LinearLayout的宽度设为充满父控件: android:layout_width="fill_parent" --> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" > <CheckBox <CheckBox android:id="@+id/item_cb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:clickable="false" android:focusable="false" android:focusableInTouchMode="false" /> </LinearLayout> </LinearLayout>
至此,完整的完成本文开发需求的布局文件就写好了。
不过最后还是留下了疑问了,不知道为什么一定要这样子来实现,而我最初用的android:layout_gravity="right"确不起作用。