Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use android:maxWidth?

Tags:

android

width

I want to set a maximum width of an edit box. So I created this small layout:

<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> 

But it doesn't work, the box could be more than 150 dp anyway. android:maxWidth="150dp" in the EditText will give the same result. I have read ( maxWidth doesn't work with fill_parent ) that setting both max- and min width to the same size should solve it:

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

But it doesn't.

I have found a solution to my problem here here: Setting a maximum width on a ViewGroup And this works great. But I guess the maxWidth attribute is here for I reason. How should it be used? Or is there any documentation on this? I have spend hours on this problem, and still doesn't understand how to use this simple attribute.

like image 295
PEK Avatar asked Dec 06 '12 19:12

PEK


2 Answers

I want to set a maximum width of an edit box.

In your example:

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

The layout_width and ems attributes are trying to set the same value. Android seems to choose the larger fill_parent value and ignores the other. And when you use this:

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

Here ems and maxWidth are trying to set the same value, again the greater value is used. So depending on what you actually want you can use:

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

or replace android:ems="10" with android:maxWidth="50dp" if you prefer to work with dp.

Lastly your LinearLayout only has one child, the EditText. Typically when this happens you can remove the LinearLayout tags and use the EditText by itself.

like image 167
Sam Avatar answered Oct 24 '22 01:10

Sam


To those who are seeing this question in recent years, we have app:layout_constraintWidth_max="225dp" now. Put your layout inside contsraint layout and use this on the view you want to have max width.

like image 37
yooneskh Avatar answered Oct 24 '22 02:10

yooneskh