Android EditText: Done instead of Enter or Word Wrap instead of Multi Line

Bryan Field picture Bryan Field · Mar 2, 2011 · Viewed 30.9k times · Source

I have a multiple line EditText that does not permit line returns. Right now I am replacing returns with some spaces as soon as they click save. Is there any way I can replace the on screen enter button with a Done button? (like it is for single line EditText)

I am aware that I should still strip out returns (\r\n|\r|\n) because the on screen keyboard is not the only way to add them.

Here is my current XML

<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
          android:minLines="3" android:gravity="left|top"
          android:inputType="textMultiLine|textAutoCorrect|textCapSentences"
          android:imeOptions="actionDone" />

Answer

Stefano picture Stefano · Sep 12, 2011

I suggest to read this article

http://savagelook.com/blog/android/android-quick-tip-edittext-with-done-button-that-closes-the-keyboard

really good example

XML:

<EditText 
    android:id="@+id/edittext_done"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter some text"
    android:imeOptions="actionDone"
    />

Custom Action Class:

class DoneOnEditorActionListener implements OnEditorActionListener {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            return true;  
        }
        return false;
    }
}

Activity Class:

public class SampleActivity extends Activity {    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_activity_layout); // sample_activity_layout contains our target EditText, target_edittext
 
        EditText targetEditText = (EditText)findViewById(R.id.target_edittext); 
        targetEditText.setOnEditorActionListener(new DoneOnEditorActionListener());
 
        // The rest of the onCreate() code
   }
}