【问题标题】:android RelativeLayout, equal spacing?android RelativeLayout,等间距?
【发布时间】:2011-04-23 15:47:39
【问题描述】:

我正在使用相对布局来创建计算器屏幕,并且我有一排标记为 1、2 和 3 的按钮。我希望它们均匀分布,但我不确定如何使用相对布局

我习惯在LinearLayout中使用android:layout_weight函数,给它们每一个赋值一个android:layout_width="fill_parent",还有一个layout_weight="1"

在计算器屏幕上实现这一点的任何方法(不指定 DP 或 PX)

这是我目前设置的,它们在 TextView(计算器输出屏幕)下按从左到右的顺序排列。对均匀空间、填充屏幕宽度有什么建议/解决方案?

    <TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/edit_text"
android:layout_margin="6px"
/>

<Button
android:id="@+id/button1"
android:text="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
/>

<Button
android:id="@+id/button2"
android:text="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_toRightOf="@+id/button1"/>

<Button
android:id="@+id/button3"
android:text="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_toRightOf="@+id/button2"
/>

【问题讨论】:

    标签: android android-relativelayout


    【解决方案1】:

    如果你想要相等的间距,你不需要RelativeLayout。正如您在问题中建议的那样,使用LinearLayout。如果需要,请将Buttons 放入LinearLayout 并将LinearLayout 放入RelativeLayout

    【讨论】:

      【解决方案2】:

      最简单的方法是在 OnCreate() 期间操作视图。

      类似:

      OnCreate(Context ctx){
        int w = getWidth();
        int h = getHeight();
        Button B1 = findViewById(R.id.button1);
        B1.setWidth(w/3);
        --repeat for button2,3 textview--
      }
      

      另一种选择是使用TableLayout where you stretch the columns 并强制按钮填充父级。这将需要您使用

      <TableLayout    android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:stretchColumns="0,1,2"
          android:layout_below="@+id/textView"> 
      <TableRow><Button
      android:id="@+id/button1"
      android:text="1"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      /><Button
      android:id="@+id/button2"
      android:text="2"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      />
      </TableRow>
      </TableLayout>
      

      【讨论】:

      • J:你的第二种方法行不通——你不能覆盖TableRow的孩子的宽度。第一个可能有效,但我持怀疑态度。
      • 我实际上将它用于基于表格布局的网格游戏。我创建了一个 NxN 表,每 N 行包含 N 个按钮,其中每个按钮的宽度都是动态设置的。
      猜你喜欢
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多