有人能告诉我如何复制在一个特定的文本视图到剪贴板,当一个按钮被按下?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
textView = (TextView) findViewById(R.id.textview);
copyText = (Button) findViewById(R.id.bCopy);
copyText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
String getstring = textView.getText().toString();
// Help to continue :)
}
});
}
我想复制文本在TextView TextView到剪贴板时,按钮bCopy按下。
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
@SuppressWarnings("deprecation")
@TargetApi(11)
public void onClickCopy(View v) { // User-defined onClick Listener
int sdk_Version = android.os.Build.VERSION.SDK_INT;
if(sdk_Version < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(textView.getText().toString()); // Assuming that you are copying the text from a TextView
Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
}
else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Text Label", textView.getText().toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
}
}
要搜索剪贴板列表,首先像这样获取剪贴板对象:
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
然后通过这个函数检查剪贴板中是否有数据:
fun isClipboardContainsData() : Boolean{
return when{
!clipboard.hasPrimaryClip() -> false
else -> true
}
}
然后使用这个函数遍历剪贴板对象,如下所示:
fun searchClipboard() : ClipData.Item? {
return if (isClipboardContainsData()){
val items = clipboard.primaryClip
val clipboardSize = items?.itemCount ?: 0
for (i in 0..clipboardSize) {
val item = items?.getItemAt(i)
return if (item != null){
return item
}else
null
}
return null
}else
null
}
这里你可以看到searchClipboard Item将返回一个类型为ClipData的项。项时,剪贴板包含ClipData的列表。项目,如果你学习clipboard的实现这就是关于ClipData的内容。单品:
public static class Item {
final CharSequence mText;
final String mHtmlText;
final Intent mIntent;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Uri mUri;
}
所以你可以在剪贴板项目中保存的内容类型可以是:
CharSequence进行
字符串
意图(支持复制应用程序快捷方式)
Uri(用于从内容提供程序复制复杂数据)