EditText word wrap

2019-04-12 20:02发布

问题:

I have this layout:

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

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

What i want is when the user enters more text than which fits into a single line, the EditText wraps the line, increases it height automatically and shows the not fitting text in the next line. The EditText should not be scrollable horizontally.

I read lots of questions related to this, but none of them helped. Currently the EditText above does not wrap the lines, and can be scrolled horizontally. I tested on Android 4.2 and 4.4.

EDIT: added complete layout.

EDIT2:

Sorry, this is my fault. I change the input type programatically in my code:

mEditText.setInputType(mInputTypes.get(question.getType()));

So with this line, i have overriden the input type from xml. I modified the code, and the multiLine input type indeed works.

回答1:

I have removed all unnecessary attributes and put only required attribute android:maxLines="20",

So it looks like this,

    <EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:maxLines="20" />


回答2:

add android:scrollHorizontally="false" and android:inputType="textMultiLine" this attribute in EditText from this post on SO

<EditText
    android:id ="@+id/editText"
    android:layout_width ="0dip" 
    android:layout_height ="wrap_content" 
    android:layout_weight ="1" 
    android:inputType="textCapSentences|textMultiLine"
    android:maxLines ="4" 
    android:maxLength ="2000"
    android:scrollHorizontally="false" />


回答3:

The only solution that worked for me:

EditText someedittext = (EditText)findViewById(R.id.someedittext);
someedittext.setMaxWidth(someedittext.getWidth());