Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to OnClick for EditText fields?

I have an EditText field, suppose the user has already entered text into it. Then the user wants to come back to edit the text again: the feature I want for this EditText field is that if you select it after it already has text in it, it clears the text for you before you can type something new in.

I tried using the EditText field's OnClick method, but this required that I select the EditText field, then click on it a second time, something that isn't obvious to anyone but me. How can I get the text to clear from the EditText field as soon as the user selects it?

like image 797
scibor Avatar asked Dec 04 '22 10:12

scibor


1 Answers

In General

You can achieve what you want to do via a combination of onFocus and clearing the text field, similar to what the two commenters under your post already suggested. A solution would look like this:

EditText myEditText = (EditText) findViewById(R.id.myEditText);
myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
        
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
        // Always use a TextKeyListener when clearing a TextView to prevent android
        // warnings in the log
        TextKeyListener.clear((myEditText).getText());
                
        }
    }
});

Please always use a TextKeyListener to "clean" EditText, you can avoid a lot of android warnings in the log this way.

But...

I would much rather recommend you to simply set the following in your xml:

<EditText android:selectAllOnFocus="true"/>

Like described here. This way your user has a much better UI-feeling to it, he or she can decide on his/her own what to do with the text and won't be annoyed because it clears out every time!

like image 141
avalancha Avatar answered Jan 18 '23 07:01

avalancha