Best way for OnClick for EditText fields?

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

I tried to use the OnClick method in the EditText field, but for this it was necessary to select the EditText field and then click on it a second time, which is not obvious to anyone except me. How can I get the text to clear from the EditText field as soon as the user selects it?

+4
source share
1 answer

Generally

You can achieve what you want to do by using the onFocus combination and clearing the text field, similar to what the two commentators have already suggested under your post. The solution will 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 TextKeyListener to β€œclear” EditText, you can avoid a lot of android warnings in the log this way.

But...

I would rather recommend that you simply install the following in xml:

 <EditText android:selectAllOnFocus="true"/> 

As described here . Thus, your user has a much better UI feeling, he or she can independently decide what to do with the text, and will not be annoyed because it is cleared every time!

+16
source

Source: https://habr.com/ru/post/1485447/


All Articles