select & copy to clipboard in TextView in Android

2019-03-05 05:16发布

问题:

Is it possible to allow the user to select and then copy text in the clipboard in a TextView?

I found this but there isn't an answer.

I have also tried to set android:textIsSelectable="true" but it didn't work.

回答1:

I fixed it by using an EditText but to avoid the problems I described in my answer to "imran khan" I found a comment about setKeyListener in the android code:

 * Be warned that if you want a TextView with a key listener or movement
 * method not to be focusable, or if you want a TextView without a
 * key listener or movement method to be focusable, you must call
 * {@link #setFocusable} again after calling this to get the focusability
 * back the way you want it.

So the problem is that when you set the flag editable to false setKeyListener is called and the focusable flag is overwritten.

To fix it, in the onCreate of my activity I added:

    tesxtView.setKeyListener(null);
    tesxtView.setFocusable(true);

By doing this I also got rid of the marks for the wrongly spelled words



回答2:

I think that starting with Lollipop, this actually works as you'd expect it (tested on my app, after I've changed a few things) :

I used this library, and changed this attribute for the file "adp_alert_dialog_material.xml", to just have the attribute you've asked about (on a TextView) :

android:textIsSelectable="true"