Select all text inside EditText when it gets focus

2019-01-04 19:33发布

I have an EditText with some dummy text in it. When the user clicks on it I want it to be selected so that when the user starts typing the dummy text gets deleted.

How can I achieve this?

9条回答
对你真心纯属浪费
2楼-- · 2019-01-04 19:59

I know you've found a solution, but really the proper way to do what you're asking is to just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.

查看更多
3楼-- · 2019-01-04 20:03
EditText dummy = ... 

// android.view.View.OnFocusChangeListener
dummy.setOnFocusChangeListener(new OnFocusChangeListener(){
    public void onFocusChange(View v, boolean hasFocus){
        if (hasFocus) && (isDummyText())
            ((EditText)v).selectAll();
    }
});
查看更多
Ridiculous、
4楼-- · 2019-01-04 20:03

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

查看更多
登录 后发表回答