EditText automatically go to a new line

纵然是瞬间 提交于 2019-11-28 09:06:37
rkrohit

ADD this to your EditText xml code

android:inputType="textMultiLine"

This will automatically moves your text to next line while entering data.

fllo

It should exist a most elegant way but this solution might help you as a clue to achieve what you want. First of all, you will need to set your EditText values as below:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text|textMultiLine|textCapSentences"
    android:maxLength="21"
    android:gravity="left"
    android:maxLines="2" />  

You must to set the maxLength attribute to 21 because the enter char (new line) will take one char in the edittext, then the user will only can write 19 chars instead of 20.
Then, you should use a TextWatcher with a boolean (used if the user removes his previous chars), and this should be as follows:

// init global boolean
private boolean isReached = false;

// in onCreate method
edittext.addTextChangedListener(new TextWatcher(){
    @Override
    public void afterTextChanged(Editable s) {
        // if edittext has 10chars & this is not called yet, add new line
        if(textEd.getText().length() == 10 && !isReached) {
            textEd.append("\n");
            isReached = true;
        }
        // if edittext has less than 10chars & boolean has changed, reset
        if(textEd.getText().length() < 10 && isReached) isReached = false;
    }
});  

Note: However, you should be careful with this code. Indeed, the user can still pressed the Key Enter and then, add new lines. Maybe these answers might help you to handle it and keep the user only "on your road": Prevent enter key on EditText but still show the text as multi-line

For the lines, do something like:

<EditText
    android:inputType="textMultiLine" <!-- Multiline input -->
    android:lines="2" <!-- Total Lines prior display -->
    android:minLines="1" <!-- Minimum lines -->
    android:gravity="top|left" <!-- Cursor Position -->
    android:maxLines="2" <!-- Maximum Lines -->
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"/>

you could also play with this parameter (Does NOT work for Android <= 3.0):

android:singleLine="false"

And for the number of characters, do something like:

EditText et= (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(20); //Filter to 20 characters
et.setFilters(filters);

or, use this other parameter,

android:maxLength="20" in the xml

prakash

For the EditText to display 2 lines. You can write like this:

android:maxLength="20"
android:maxLines="2"
android:singleLine="false"
android:layout_width="Your Choice"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!