Android EditText: Done instead of Enter or Word Wr

2019-03-18 02:23发布

问题:

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

回答1:

android:inputType="textEmailAddress|textEmailSubject"

You need to set the input type as email address or email subject. Either one will give you your desired result. shouldAdvanceFocusOnEnter() is a private method in TextView which determines whether to enter a new line or move focus to next field.



回答2:

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


回答3:

If you're using android:inputType="textMultiLine|..." in your XML, or using the corresponding Java code:

editField.setInputType(
    InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);

then the only solution to show a ✔︎ Done or