How to dynamically select text from EditText OnCli

2019-01-12 08:27发布

问题:

I want to use the android select text functionality on OnClickListener rather than onlongclicklistener. Is there any way to do this? Can anybody help me regarding this? Thanks

回答1:

with xml:

android:selectAllOnFocus="true"

with code (option1):

    yourEditText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //((EditText)v).selectAll();
            ((EditText)v).setSelection(startValue, stopValue);
        }
   });

with code (option2):

yourEditText.setOnFocusChangedListener(new OnFocusChangedListener(){
    @Override
    public void onFocusChange(View v, boolean hasFocus){
        if (hasFocus){
            //((EditText)v).selectAll();
            ((EditText)v).setSelection(startValue, stopValue);
        }
    }
});


回答2:

This answer gives you several options if you want to select all the text.

If not then use an onclicklistener and call setSelection on your EditText.

EDIT:

theEditText.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        EditText editText = (EditText)view;
        editText.setSelection(editText.getText().length()-1); // selects all the text
    }
});


回答3:

A totally different approach would be to try calling performLongClick from your EditText's onClick handler. This might let you use the default long click functionality, but call it from your onClick.

theEditText.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        EditText editText = (EditText)view;
        editText.performLongClick();
    }
});