Search code examples
androidtextviewandroid-edittextclipboardmanager

Selecting Text from a TextView or EditText


I have a few TextView and a few EditText from which I would like to select a substring of the data for copyingfor API level 10 and above.I have implemented an OnLongClickListener for the problem but it(understandably) throws an ArrayOutOfBoundsException:

   public boolean onLongClick(View v) {
    // TODO Auto-generated method stub
    //copy
    longPressedView=v;
    startSelection=((TextView)v).getSelectionStart();
    endSelection=((TextView)v).getSelectionEnd();
    Log.d(TAG, "Selection starts at "+startSelection+" and ends at "+endSelection);
    if(startSelection>endSelection)
    {
        startSelection=startSelection+endSelection;
        endSelection=startSelection-endSelection;
        startSelection=startSelection-endSelection;
        Log.d(TAG, "After interchanging positions selection starts at "+startSelection+" and ends at "+endSelection);
    }
    mSelectedText=((TextView)v).getText().toString().substring(startSelection, endSelection);
    mActionMode=startActionMode(actionModeCallback);
    return true;
}

I have thought upon implementing the OnTouchListener,but that would only return the x and y positions which would be of no use to me.

 java.lang.StringIndexOutOfBoundsException: length=93; regionStart=-1; regionLength=0
 at java.lang.String.startEndAndLength(String.java:583)
 at java.lang.String.substring(String.java:1464)
 at com.example.clipboardtest.MainActivity.onClick(MainActivity.java:139)
 at android.view.View.performClick(View.java:4240)
 at android.view.View$PerformClick.run(View.java:17721)
 at android.os.Handler.handleCallback(Handler.java:730)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:137)
 at android.app.ActivityThread.main(ActivityThread.java:5103)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:525)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 at dalvik.system.NativeStart.main(Native Method)

Solution

  • First of all add this property in textview in your xml : -

    android:textIsSelectable="true"
    

    Then use this code :-

        t = (TextView)findViewById(R.id.textView1);
        t.setOnLongClickListener(new View.OnLongClickListener() {
    
            @Override
            public boolean onLongClick(View v) {
    
                int start = t.getSelectionStart();
                int end = t.getSelectionEnd();
                if(start == -1 && end == -1){
                    return true;
                }
                String mSelectedText=((TextView)v).getText().toString().substring(start, end);
                System.out.println(mSelectedText);
    
                return false;
            }
        });