开发者

Clearing a multiline EditText

开发者 https://www.devze.com 2023-02-06 10:21 出处:网络
I am trying to clear a multiline EditText field inside the OnEditorActionListener.onEditorAction method.

I am trying to clear a multiline EditText field inside the OnEditorActionListener.onEditorAction method.

But using any of the obvious ways i.e.

((EditText) view).getEditableText().clear();
((EditText) view).getEditableText().clearSpans(); 
((EditText) view).setText("");

only clears the visible characters - leaving the the ne开发者_如何学Cwlines in the field (which then have to be manually deleted).

Is there way to 'completely' clear a multiline EditText field ? (or at least - does anybody know why the above don't work ?)


Solved (in a minute after a good night's sleep) - the newline was being added after clearing the text because the onEditorAction method implementation was returning false (for other reasons).

Returning true indicates that the 'enter' has been processed/consumed and the clear() behaves as expected:

edittext.setOnEditorActionListener(new OnEditorActionListener() { 
    @Override
    public boolean onEditorAction(TextView view,int actionId,KeyEvent event) {
           post(view.getText().toString());

           ((EditText) view).getEditableText().clear();

           return true;
         }
     });


I don't have an IDE here to test, but you could give it a try:

  • ((EditText) view).clearComposingText() It's a inherit method from TextView
  • Not so elegant but maybe functional: setSingleLine = true and then false again. Maybe useful until someone can provide something better...


There is a way with setMaxLines:

yourEditText.getEditableText().clear();
yourEditText.setMaxLines(1);


Maybe I'm feeling a bit too lucky but:

((EditText) view).setText(null);


I used this when I had a clear button on my app

            Button clearButton = (Button)findViewById(R.id.clear);

    clearButton.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View v) {

            number = (EditText) findViewById(R.id.text_reading);

            number.setText("");

            }
        });
0

精彩评论

暂无评论...
验证码 换一张
取 消