【问题标题】:Android: Layout always 2/3 screenAndroid:布局总是 2/3 屏幕
【发布时间】:2017-07-25 18:30:42
【问题描述】:

我在滚动视图中添加了许多视图(<include>)。这些布局是这样的:

<RelativeLayout
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="18dp"
        android:layout_marginRight="18dp"
>
</RelativeLayout>

这就是我将这些布局包含到fragment 布局中的方式:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
>
    <ScrollView android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:orientation="vertical"
        >
            <include layout="@layout/one"/>
            <include layout="@layout/two"/>
            <include layout="@layout/three"/>
        </LinearLayout>
        </ScrollView>
</LinearLayout>

如何使这 3 种布局的高度始终为屏幕的 2/3。我希望它始终位于每台设备屏幕的 2/3 处。 layout_weight 无法按预期工作。

【问题讨论】:

  • 为什么不以编程方式获取设备高度并以 2/3 比例设置为您想要的视图。
  • @AdnanMaqbool 感谢您的评论,但老实说,我需要发布另一个问题如何做到这一点。你能告诉我路吗?
  • 检查我更新的答案。希望有帮助

标签: android layout


【解决方案1】:

您可以通过多种方式获取屏幕的宽度和高度

public static int getScreenWidth() {
    return Resources.getSystem().getDisplayMetrics().widthPixels;
}

public static int getScreenHeight() {
    return Resources.getSystem().getDisplayMetrics().heightPixels;
}

getScreenHeight() 将返回总高度

您可以使用这个高度并设置参数如下:

desired_height_params = getScreenHeight() *2/3

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, 
    desired_height_params
);
linLayout.setLayoutParams(lp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 2011-09-09
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多