[英]Cross-version (starting api 7 (eclair)) copy paste in Android?
I want to enable copy paste in a TextView. 我想在TextView中启用复制粘贴。
I found these very nice explanations in Android docs: http://developer.android.com/guide/topics/clipboard/copy-paste.html 我在Android文档中找到了这些非常好的解释: http : //developer.android.com/guide/topics/clipboard/copy-paste.html
But it works only starting at version 11 - honeycomb! 但它只能从版本11开始 - 蜂窝!
I need something which also works for the majority of users at this point of time, means it has to work also for gingerbread, froyo and eclair. 我需要的东西在这个时间点也适用于大多数用户,这意味着它必须也适用于姜饼,froyo和eclair。
What do I use? 我该用什么?
Use the ClipboardManager
found in the android.text
package. 使用android.text
包中的ClipboardManager
。 They moved it to a different package because they started supporting clipping things other than text, but for backwards compatibility you can still use it under the old name. 他们将它移动到另一个包中,因为他们开始支持除文本之外的剪辑内容,但为了向后兼容,您仍然可以使用旧名称来使用它。
You still wind up with stuff like: 你仍然喜欢这样的东西:
ClipboardManager cm=(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
cm.setText("something");
Here is a sample project demonstrating this. 这是一个示例项目 。
These are the completely cross-platform and exception-free ways to copy plain text to clipboard and paste plain text from clipboard in Android: 这些是将纯文本复制到剪贴板并从Android中的剪贴板粘贴纯文本的完全跨平台且无异常的方法:
@SuppressLint("NewApi") @SuppressWarnings("deprecation")
public void copy(String plainText)
{
if (android.os.Build.VERSION.SDK_INT < 11)
{
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null)
{
clipboard.setText(plainText);
}
}
else
{
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null)
{
android.content.ClipData clip = android.content.ClipData.newPlainText("text", plainText);
clipboard.setPrimaryClip(clip);
}
}
}
@SuppressLint("NewApi") @SuppressWarnings("deprecation")
public String paste()
{
if (android.os.Build.VERSION.SDK_INT < 11)
{
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null)
{
return (String) clipboard.getText();
}
}
else
{
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null && clipboard.getPrimaryClip() != null && clipboard.getPrimaryClip().getItemCount() > 0)
{
return (String) clipboard.getPrimaryClip().getItemAt(0).getText();
}
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.