A better way to OnClick for EditText fields?

回眸只為那壹抹淺笑 提交于 2019-12-10 15:13:45

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/17025911/a-better-way-to-onclick-for-edittext-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!