将layout_weight与minWidth结合使用

12

我有一个布局,想要使用layout_weight(1:2)将其分成两个视图。但是,我希望左侧视图至少有400dp的宽度。

例如,如果左侧视图使用权重达到420dp宽度,则保持不变,但如果小于400dp,则让它保持为400dp并将其他视图全部给予余下的宽度。

这是我尝试过但并没有成功的布局:

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

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:minWidth="400dp"
            android:background="@android:color/holo_blue_bright"/>

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:background="@android:color/holo_green_light"/>

    </LinearLayout>

请帮忙, 谢谢!


据我所见,您必须以编程方式完成此操作。但在此之前,我建议重新考虑您的用户界面。您正在尝试做的似乎有些多余。 - JanithaR
2个回答

2
我认为这是你所需要的内容:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <View
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:minWidth="400dp"
        android:background="@android:color/holo_blue_bright"/>

    <View
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_light"/>

</LinearLayout>

基本上,让第一个布局占据所需的空间,但不少于400dp。第二个布局将占据所有剩余的空间。与涉及“weight”时的所有情况一样,请确保两个子项所需的宽度空间小于父级可以提供的空间,否则您将会有屏幕外的事物。
注意:我在手机布局上尝试了它,但在纵向方向上400dp超出了屏幕,因此似乎第一个布局占据了所有空间,因此请务必在您希望布局跨越的方向上使用大于400dp的设备进行测试 :-)

抱歉在问题中没有写清楚,但是左侧视图是一个动态布局,应该从其父视图获取大小。无论如何,谢谢! - Yaniv
它不会改变任何东西。想法是不要对其施加重量。如果您实际上通过“LayoutParams”设置宽度而不将其设置为“wrap_content”,则无关紧要。也许您需要用LinearLayout替换您的View标签,并将Views放置在其中。 - N.T.

-1
Try this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:weightSum="3" >

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_bright"
        android:minWidth="400dp" />

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="@android:color/holo_green_light" />

</LinearLayout>

将LinearLayout的android:layout_width="match_parent"替换为android:layout_width="wrap_content"。 - Pranay Narvankar

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