how to select text with a single click in the Edit

2019-08-28 06:45发布

问题:

Source code below is not working

    public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_book_page);

             book_page = (EditText) findViewById(R.id.activity_book_page_text);
             book_page.setText("Google is your friend.", TextView.BufferType.EDITABLE);

             book_page.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        book_page.setSelection( 9, 15);
                         //book_page.requestFocus();


                    }
               });

             book_page.setOnFocusChangeListener(new OnFocusChangeListener(){
                    @Override
                    public void onFocusChange(View v, boolean hasFocus){
                        if (hasFocus){
                            book_page.setSelection( 9, 15);
                        }
                    }
                });

 <EditText
        android:id="@+id/activity_book_page_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:ems="10"
        android:inputType="textMultiLine"
        android:selectAllOnFocus="true" >

        <requestFocus />
    </EditText>

回答1:

Use this piece of code in your .java file:

editText.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        editText.setSelection(0, editText.getText().length() - 1);
    }
}


回答2:

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);
    }
   });

And also try like this:

Call EditText.setSelectAllOnFocus(boolean selectAllOnFocus) to select all text on focus.

Set a click listener to your EditText and in onClick call edittext.selectAll();



回答3:

    editText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            editText.performLongClick();
        }
    });

An EditText's default long-click behaviour is to select the word that has been tapped, then drag the selection markers, so just call performLongClick() in onClick().