Skip to content

Instantly share code, notes, and snippets.

@z8888q
Created March 22, 2013 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z8888q/5219273 to your computer and use it in GitHub Desktop.
Save z8888q/5219273 to your computer and use it in GitHub Desktop.
Android developer: make your text views selectable
September 02, 2012
Historically, support for text selection and copy/paste on Android has been limited to text input fields only. (Some specific applications like the Browser and Gmail have also included their own implementations of text selection from other areas). Fortunately, starting with Android 3.0 the TextView component has built-in support for a consistent, system-wide selection & copying system.
However, this feature is not enabled by default for text views. Very few developers choose to enable it when appropriate: many probably don't even know of its existence. Enabling it is simple and only takes one extra attribute:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true" />
(Or programmatically:)
textView.setTextIsSelectable(true);
And you're done. The text can now be selected and copied by long clicking it. This will start the selection mode:
In the action bar: select all and copy.
(A note on backwards compatibility: adding this attribute to a TextView in XML is perfectly safe. Older versions of Android will simply ignore it. If you want to set it programmatically, wrap the call in an if statement to check the version first. You will need to build your app using at least the 3.0 SDK, but you can set the minimum version to a lower Android version in the manifest.)
Be sure to enable this feature in areas of your application that it is useful in. For example, text selection will not work in a list view, but you can enable it in the viewing UI for an individual list item. Your users will thank you.
让TextView支持长按弹出系统自带的拷贝、粘贴功能,发现国内外的论坛提供的解决方法都不怎么理想。多数用editview来模仿,不过实现的效果实在不怎么好。
从android sdk 11起google添加了新api TextIsSelectable控制TextView是否支持拷贝、粘帖功能,不过这个功能在v11以下则不那么好彩了。
查阅TextView源码发现setTextIsSelectable实际调用的是Editor类的相应方法,而Editor里面控制了拷贝、粘帖功能。顺藤摸瓜通过反射获取到mEditor变量再调用setTextIsSelectable里调用的方法,调出拷贝、粘帖功能。似乎这是个很好的方法。不过很遗憾在系统为4.x的不同设备里测试发现都不成功,不是没有mEditor变量就是mEditor返回null。看来这个Editor在不同的厂商也有不同的实现,google也把这个类标为hide。
又仔细看了看TextView源码,发现setTextIsSelectable顺序调用了以下几个函数
Java代码
setFocusableInTouchMode(true);
setFocusable(true);
setClickable(true);
setLongClickable(true);
setMovementMethod( ArrowKeyMovementMethod.getInstance());
setText(tv.getText(),BufferType.SPANNABLE );
在v4、v8系统测试顺利调出拷贝、粘帖功能。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment