Android XML - 如何让项目对齐很远的左边,中间和最右边
问题描述:
我有这个XML代码,它会生成一个按钮,一个textview和另一个按钮,我该如何去让按钮出现在最左边, textview在中心和最右边的最后一个按钮?Android XML - 如何让项目对齐很远的左边,中间和最右边
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel">
</Button>
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Place">
</TextView>
<Button android:id="@+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save">
</Button>
</LinearLayout>
答
您需要使用weight属性。把它想象成让android知道它应该给每个项目的宽度的百分比。
您需要设置宽度0dip所有3项,并添加重量属性
<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_width="0dip"
android:layout_weight="2" >
</Button>
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Place"
android:layout_width="0dip"
android:layout_weight="1" >
</TextView>
<Button android:id="@+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_width="0dip"
android:layout_weight="2" >
</Button>
玩弄权重值,你就会明白它是如何工作:)
此之后,你可以使用重力属性将文本移动到中心/左侧或右侧。
答
我会推荐使用RelativeLayout,它使事情变得更容易。
使用RelativeLayout的你就可以这样做,你将能够直接连接这些按钮到远边他们对准父后设置TextView的父或centerin父
无论是中心水平或者直接将它们连接到textview的两侧,可能会添加一点填充,并且你已经获得了空间。
答
如果你想保持LinearLayout,你需要做的是:创建一个TableRow,然后把所有的项目(包括按钮和Textview)。这将创建一条整齐排列的所有项目的直线。此代码适合我,对不起,我无法忍受它的一个截图(新,并没有足够的声望点),但它对我有用,我希望它可以帮助你。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_marginRight="30dp"
android:layout_marginLeft="10dp">
</Button>
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Place"
android:layout_gravity="center_horizontal"
android:layout_marginRight="30dp">
</TextView>
<Button android:id="@+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="right">
</Button>
</TableRow>
</LinearLayout>