繁体   English   中英

Android RelativeLayout同步宽度

[英]Android RelativeLayout sync width

我有一个LinearLayout ,其中包含其他两个RelativeLayouts (水平方向)。 我在运行时不知道左侧RelativeLayout的宽度。 是否可以同步两个布局? 如果左侧的RelativeLayout的宽度为100dp ,则右侧的RelativeLayout的宽度也应为100dp 或两者都应为50dp

我可以在XML文件中处理此问题,还是可以通过代码并将LayoutParams设置为相同的值来完成此工作?

在每个RelativeLayout中将宽度设置为0dp,将权重设置为1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal" >

  <RelativeLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1" >
  </RelativeLayout>

  <RelativeLayout
      android:layout_width="0dp"
      android:layout_height="match_parent" 
      android:layout_weight="1">
  </RelativeLayout>

</LinearLayout>

如果它是动态宽度,则没有xml方式。 在xml中,您只能:

  1. 为两个相对布局设置固定宽度
  2. 设置线性布局的固定宽度(或匹配父级),相对布局使用width =“ 0dp”和weight = 1

如果第一个布局的宽度未知,则需要使用一些技巧:

 firstRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        public void onGlobalLayout() {
            secondRelativeLayout.getLayoutParams().width=firstRelativeLayout.width;
            secondRelativeLayout.requestLayout();
        }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM