【问题标题】:android layout dynamic sizingandroid布局动态调整大小
【发布时间】:2011-11-20 14:54:57
【问题描述】:

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

我是否必须浏览每个页面并自己计算每个项目的特定宽度,或者有没有办法按照“fill_parent / 2”的方式放置一些东西?

编辑:忘记提及可能是关键说明 - 我所做的几乎所有事情都在 RelativeLayouts 中,我在这个项目中很少使用 LinearLayouts。

【问题讨论】:

    标签: android xml layout dynamic width


    【解决方案1】:

    如果您有一个左右齐平的 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 上设置重力来调整它。

    【讨论】:

    • weightSum 是否只影响“fill_parent”属性?
    • 没有。 weightSum 仅表示“它们应该加起来多少”。因此,您的子元素将完全占据它们的 layout_weight / parent 的 weightSum * parent 的实际宽度。前任。 Layout = 400px, weightSum = 4, layout_weight of child = 1. Child 的宽度为 100px (1 / 4 * 400 = 100)
    【解决方案2】:

    使用具有两列的表格视图,其中每一列都被拉伸并具有文本视图。然后隐藏第二个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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2012-02-20
      • 1970-01-01
      相关资源
      最近更新 更多