如何创建具有最小和最大高度的布局?

3
我有两个布局layout1和layout2,它们都在垂直线性布局中。
例如,标准的layout1高度为300dp(对于小尺寸显示器而言是较大的高度),
这样在小尺寸显示器上几乎占据了整个视图高度。但我想让layout1的最大高度占视图的50%。
如果我在大尺寸显示器上将高度设置为视图高度的50%,则会有一些空间浪费。
enter image description here
如果我在小尺寸显示器上将高度设置为300dp,则只有layout1。
enter image description here
因此,我必须限制layout1的高度,在小尺寸显示器上为重量的50%,在大尺寸显示器上为300dp。
如何将这些限制应用到我的layout1中?
3个回答

2
在运行时,您可以确定LinearLayout1占用的空间有多少,并仅在它占据了超过屏幕一半的空间时调整其高度。为此,请使用以下代码。
假设您已将LinearLayout1的ID设置为R.id.LL1,则使用此代码,您可以请求Android将LL1的高度调整为50%。
int screenHeight, screenWidth;

//Code to determine screen's height and width.

Display display = getWindowManager.getDefaultDisplay();
if (android.os.Build.Version.SDK_INT>=13) {
    Point size = new Point();
    display.getSize(size);
    screenHeight = size.x;
    screenWidth = size.y;
}
else {
    screenWidth = display.getWidth();
    screenHeight = display.getHeight();
}


LinearLayout ll = (LinearLayout) findViewById(R.id.LL1);

int layoutHeight = ll.getLayoutParams().height; // gets layout's height

if ((layoutHeight * 2) > screenHeight) { 

    // true when LL1 takes more than half of screen, good time to set it back to 50% height

    ll.getLayoutParams().height = screenHeight/2;
    ll.requestLayout(); //Forces layout to be adjusted.
}

else {
//All good, no work required, so skip this else block
}

嗨,谢谢你的关注。getWindowManager是什么?它是一个库,还是一个类?我需要在我的项目中添加什么吗?当我使用你的代码时,Eclipse无法识别它。 - max
@max 参考 此链接。这是 Activity 类提供的一个处理窗口(在 Android 上)的方法。 - Shishir Gupta

1

你知道权重是什么吗?

如果你想要两个布局(L1 50%)(L2 50%)的高度,请使用以下代码:

<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="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:weightSum="1"
    >
        <LinearLayout 
        android:orientation="horizontal"
        android:layout_height="0dp"
        android:layout_weight=".5"
        android:layout_width="match_parent"
         >
    </LinearLayout>

        <LinearLayout 
        android:orientation="horizontal"
        android:layout_height="0dp"
        android:layout_weight=".5"
        android:layout_width="match_parent"
         >
    </LinearLayout>
</LinearLayout>

如果您想在不同屏幕大小(大、小)中使用不同的百分比,请为每个屏幕大小创建另一个具有相同名称但不同权重的xml文件。
例如:res/layout-large/activity_main.xmlres/layout-small/activity_main.xml,只需更改权重即可。
更多信息:http://developer.android.com/guide/practices/screens_support.html

0
我通过比较ScrollView的高度和屏幕宽度(根据您的要求可以与高度进行比较)来解决了这个问题:
if (myScrollView.getHeight > ((int)(screenWidth * 0.8))) {

    myScrollView.getLayoutParams().height = (int)(screenWidth * 0.85);

}

实际上,我正在动态添加视图。一旦ScrollView的高度达到一定限制,就会固定高度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接