线性布局中等大并且不超过50dp的2个文本框

请问线性布局中,水平放置有2个文本框,线性布局的宽度不确定,取决于屏幕大小,如果希望两个文本框等大,即两个都是 layout_weight =1,并且这2个文本框最大都不超过50dp,但是如果设置了两个都是 layout_weight =1,maxWidth就可能会失效吧? 请问这个怎么实现比较稳妥? 假定不能将这2个文本框放置于一个100dp的线性布局中。就是其必须置于长度不确定的一个线性布局中,不能再嵌套使用线性布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="文本框1"
            android:textColor="@color/white"
            android:background="@color/black"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/black"
            android:textColor="@color/white"
            android:text="文本框2"
            android:layout_marginStart="10dp"/>
        
        
    </LinearLayout>

</LinearLayout>

这样写不能满足需求吗?

img

【以下回答由 GPT 生成】

要在一个不确定宽度的线性布局中实现等大且最大宽度不超过50dp的两个文本框,可以通过以下步骤来实现:

  1. 创建一个水平的线性布局,设置宽度为 match_parent 或 wrap_content,具体根据你的需求而定。

  2. 在线性布局中添加两个文本框,设定宽度为 0dp(这是因为在使用 layout_weight 属性时,宽度应设为0dp)。

  3. 设置文本框的 layout_weight 属性为1,这将使它们平均分配剩余的空间。

  4. 将文本框的最大宽度限制为50dp。可以通过设置文本框的 maxWidth 属性来实现。

下面是一个示例的代码片段,展示了如何使用XML布局文件来实现这个需求:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:maxWidth="50dp"
        android:text="文本框1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:maxWidth="50dp"
        android:text="文本框2" />

</LinearLayout>

请注意,这个解决方案是基于使用XML布局文件的情况。如果你使用的是其他布局方式或代码动态创建布局,请提供更多关于你的具体实现方式的信息,以便我能够给出更加针对性的解决方案。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^