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条回答
Root(大扎)
2楼-- · 2019-01-04 19:40

Managed it by calling focus and selection on program

{
editabletext.requestFocus();
editabletext.selectAll();
}
查看更多
Luminary・发光体
3楼-- · 2019-01-04 19:44

I tried an above answer and didn't work until I switched the statements. This is what worked for me:

    myEditText.setSelectAllOnFocus(true);
    myEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onClickMyEditText();
        }
    });

   private void onClickMyEditText() {
       if(myEditText.isFocused()){
        myEditText.clearFocus();
        myEditText.requestFocus();
       }else{
           myEditText.requestFocus();
           myEditText.clearFocus();
       }
   }

I had to ask if the focus is on the EditText, and if not request the focus first and then clear it. Otherwise the next times I clicked on the EditText the virtual keyboard would never appear

查看更多
Evening l夕情丶
4楼-- · 2019-01-04 19:47

You can also add an OnClick Method to the editText after

_editText.setSelectAllOnFocus(true);

and in that:

_editText.clearFocus();
_editText.requestFocus();

As soon as you click the editText the whole text is selected.

查看更多
迷人小祖宗
5楼-- · 2019-01-04 19:54

Why don't you try android:hint="hint" to provide the hint to the user..!!

The "hint" will automatically disappear when the user clicks on the edittextbox. its the proper and best solution.

查看更多
走好不送
6楼-- · 2019-01-04 19:55

You can try in your main.xml file:

android:selectAllOnFocus="true"
查看更多
唯我独甜
7楼-- · 2019-01-04 19:57
editText.setSelectAllOnFocus(true);

This works if you want to do it programatically.

查看更多
登录 后发表回答