【问题标题】:RelativeLayout - Positioning item below the lowest of two Views相对布局 - 将项目定位在两个视图中最低的下方
【发布时间】:2012-04-09 10:23:02
【问题描述】:

我在 RelativeLayout 中有一个 TextView(宽度:fill_parent),我想确保它位于其上方并排的两个视图下方,具有动态宽度和高度。这意味着,有时左视图更高,有时右视图更高。

我尝试设置两个“低于”参数,但这当然是不允许的。 我尝试通过代码对其进行修改(将 XML 设置在 txt TextView 下面,img 是它旁边的 ImageView):

if (txt.getHeight() + txt.getTop() < img.getHeight() + img.getTop()) {
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
                    params.addRule(RelativeLayout.BELOW, R.id.image);
                    txtDetails.setLayoutParams(params);
                }

(txtDetails 是我想要的两个视图下方的那个)。

当这不起作用时(没有任何改变),我将 txtDetails 放在它自己的 RelativeLayout 中,它位于包含两个视图并且有效的 RelativeLayout 下方。但是,我觉得 RL 应该能够处理这种情况,而无需创建新的 RL。可能吗?或者定位此视图的最佳方式是什么?

谢谢

【问题讨论】:

    标签: android android-ui


    【解决方案1】:

    为什么不使用表格布局?它在 2 行中完全符合您的要求。

    首先在一行中添加两个变量视图,然后添加另一行包含您的文本视图。

    像这样:

    <TableLayout
        android:id="@+id/center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TableRow >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="150sp"
            android:layout_height="wrap_content"
            android:text="@string/lorem_short" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="150sp"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:text="@string/lorem_long" />
        </TableRow>
        <TableRow>
        <TextView
            android:id="@+id/textView3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5sp"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
        </TableRow>
    </TableLayout>
    

    【讨论】:

      【解决方案2】:

      您的代码可能存在问题:
      您正在视图上调用 getHeight(),如果尚未完成布局传递,则可能会返回 0。您应该像这样将整个代码放在 GlobalLayoutListener 中:

      getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
         @Override
         public void onGlobalLayout() {
             // your code here...
             txt.requestLayout(); // Add this to ensure your changes are applied.
         }
      }
      

      PS。你可以打电话给txt.getBottom() 而不是txt.getHeight() + txt.getTop()

      【讨论】:

        猜你喜欢
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        相关资源
        最近更新 更多