30

我想设置编辑框的最大宽度。所以我创建了这个小布局:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:maxWidth="150dp" > 

    <EditText 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:ems="10" /> 
</LinearLayout> 

但它不起作用,盒子无论如何可能超过150 dp。android:maxWidth="150dp"EditText将给出相同的结果。我已阅读(maxWidth 不适用于 fill_parent)将最大和最小宽度设置为相同大小应该可以解决它:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:maxWidth="50dp"
        android:minWidth="50dp" />

但事实并非如此。

我在这里找到了解决我的问题的方法: Setting a maximum width on a ViewGroup 这很好用。但我想这个maxWidth属性是出于我的原因。应该如何使用?或者有这方面的任何文件吗?我在这个问题上花了几个小时,但仍然不明白如何使用这个简单的属性。

4

2 回答 2

36

我想设置编辑框的最大宽度。

在您的示例中:

<EditText 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:ems="10" /> 

和属性试图设置相同的值layout_widthemsAndroid似乎选择了较大的fill_parent值而忽略了另一个。当你使用它时:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:maxWidth="50dp"
    android:minWidth="50dp" />

在这里emsmaxWidth试图设置相同的值,再次使用更大的值。因此,根据您实际想要的内容,您可以使用:

<EditText 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:ems="10" /> 

或者如果您更喜欢使用 dp 则android:ems="10"替换为。android:maxWidth="50dp"

最后,您的 LinearLayout 只有一个孩子 EditText。通常,当这种情况发生时,您可以删除 LinearLayout 标签并单独使用 EditText。

于 2012-12-06T20:00:36.407 回答
29

对于那些近年来看到这个问题的人,我们app:layout_constraintWidth_max="225dp"现在看到了。将您的布​​局放在约束布局中,并在您想要最大宽度的视图上使用它。

于 2020-04-27T03:59:35.890 回答