2

In my app I have EditText element but I use it like TextView (it is not editable).

I want to select all text in this field by click on some button. I do it with the next code

Selection.setSelection((Spannable) et.getText(),0, et.getText().length());
et.setSelected(true);

It works fine and text selected but after that I can not change ends of selection. How can I call selection handles programmatically?

Also I blocked OnLongClick because I need only Copy option and add it in custom button.

lubart
  • 1,746
  • 3
  • 27
  • 35

3 Answers3

2

You need to make sure that the EditText has the property android:textIsSelectable="true" in the layout file.

You can also do the same thing by et.setTextIsSelectable(true);

But please make sure that your application's minSdkVersion is 11 to use this.

Tanmay Mandal
  • 39,873
  • 12
  • 51
  • 48
  • Thanks for answer! I found this way but I need some code for minSdkVersion=8. Is it possible? may be some workaround? I only need a possibility custom select text and copy it but without soft keyboard and context menu. – lubart Apr 22 '13 at 10:51
0

Try some thing like this

 et.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
            int strt=   et.getSelectionStart();
            int end =   et.getSelectionEnd();
                Log.i(" Selectionm",et.getText().toString().substring(strt, end));
                return false;
            }
        });
Arun C
  • 9,035
  • 2
  • 28
  • 42
0

With required android:textIsSelectable="true", call the following method with EditText or TextView as parameter:

private fun forceSelectionWithHandlesVisible(view: TextView) {
    if (!view.hasSelection()) {
        view.performLongClick()
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
        // Hack required to make the selection handles visible when focus programmatically
        val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_UP, 0F, 0F, 0)
        with(event) {
            view.onTouchEvent(this)
            recycle()
        }
    }
}

Worked for me.

jhavatar
  • 3,236
  • 1
  • 18
  • 11