Recently, I have encountered the need to have the function of copying text in the project. One of the difficulties is how to get the content of the item in the listview, not to mention the code.
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
item_id = info.position;
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.menu_main,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_copy://复制
CopyToClipboard(this,data.get(item_id).content);
break;
default:
return super.onContextItemSelected(item);
}
adapter.notifyDataSetChanged();
return true;
}
public static void CopyToClipboard(Context context,String text){
ClipboardManager clipboard = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip=ClipData.newPlainText("simple text",text);
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "你已复制到剪切板", Toast.LENGTH_SHORT).show();
}
menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<!--<item android:id="@+id/action_settings" android:title="删除"-->
<!--android:orderInCategory="100" app:showAsAction="never" />-->
<item android:id="@+id/action_copy" android:title="复制"
android:orderInCategory="100" app:showAsAction="never" />
<!--<item android:id="@+id/action_pasty" android:title="粘贴"-->
<!--android:orderInCategory="100" app:showAsAction="never" />-->
<!--<item android:id="@+id/action_add" android:title="清空"-->
<!--android:orderInCategory="100" app:showAsAction="never" />-->
</menu>
One of the most important knowledge points here is an attribute of TextView. Only by setting it can you freely choose to copy and paste
android:textIsSelectable="true"
data is my data collection