android布局动态调整大小

时间:2011-09-19 21:52:48

标签: android xml layout dynamic width

对于我正在为程序设计的页面中的许多“标题”TextView,我希望它们是parent.Width / 2然后正确对齐。虽然在Java中编写代码相当容易,但我试图在XML布局中尽可能地做,以避免XML-Java代码交叉,直到最后一点(按下按钮,完成页面等)。

我是否必须自己浏览每个页面并计算每个项目的特定宽度,或者有没有办法放置“fill_parent / 2”的内容?

编辑:忘了提一下可能是关键注意事项 - 我几乎所做的一切都是在RelativeLayouts中,我在这个项目中对LinearLayouts的用处很少。

2 个答案:

答案 0 :(得分:4)

如果你有一个向左和向右齐平的LinearLayout,你可以执行以下操作:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:gravity="left"
    android:orientation="horizontal">
    <TextView
        android:layout_weight="1"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:text="I take up half the width!!!1" />
</LinearLayout>

通过在父级上设置weightSum,您说儿童的权重应该等于该数量。通过将单个孩子的体重设置为其中的一半,它将占用一半的空间。确保将子项的宽度设置为0,以便它知道使用权重值来计算相对于其父项的空间。

然后,您可以通过在父LinearLayout上设置重力来对齐它。

答案 1 :(得分:0)

使用包含两列的tableview,其中每列都被拉伸并具有文本视图。然后隐藏第二个textview

<TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1">
  <TableRow>
    <TextView android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Set Item Name "/>
    <TextView android:id="@+id/hiddenTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="invisible"/>
  </TableRow>
</TableLayout>