如何使用android:maxWidth?

PEK*_*PEK 24 android width

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

<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> 
Run Code Online (Sandbox Code Playgroud)

但它不起作用,无论如何,盒子可能超过150 dp.android:maxWidth="150dp"EditText意志中会给出相同的结果.我已经阅读(maxWidth不能与fill_parent一起使用)将max-和min宽度设置为相同的大小应解决它:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:maxWidth="50dp"
        android:minWidth="50dp" />
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.

我在这里找到了解决问题的方法: 在ViewGroup上设置最大宽度 这很好用.但我想这个maxWidth属性就是我的理由.该如何使用?或者有这方面的文件吗?我花了好几个小时来处理这个问题,但仍然不明白如何使用这个简单的属性.

Sam*_*Sam 29

我想设置一个编辑框的最大宽度.

在你的例子中:

<EditText 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:ems="10" /> 
Run Code Online (Sandbox Code Playgroud)

layout_widthems属性试图设置相同的值.Android似乎选择较大的fill_parent值而忽略了另一个.当你使用这个时:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:maxWidth="50dp"
    android:minWidth="50dp" />
Run Code Online (Sandbox Code Playgroud)

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

<EditText 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:ems="10" /> 
Run Code Online (Sandbox Code Playgroud)

或更换android:ems="10"android:maxWidth="50dp",如果你喜欢用DP工作.

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

  • 从我所见的`minWidth`和`layout_width ="wrap_content"`(和`ems`)都设置了基本值,它类似于`maxWidth`但是Android在其中选择了_smallest_值.这就是为什么如果设置`layout_width ="wrap_content"`,`maxWidth ="500dp"`和`minWidth ="500dp"`,除非屏幕小于500dp,否则布局将是500dp宽. (2认同)

小智 27

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