我已经使用自定义 ActionMode 回调实现了相同的功能。我们可以通过设置将自定义操作模式回调设置为回收器视图项的特定文本视图textView.customSelectionActionModeCallback在recyclerViewAdapter的onBindViewHolder中。在自定义回调中,我们可以使用当前位置和选定的文本。
onBindViewHolder 看起来像这样。
public void onBindViewHolder(myViewHolder holder, int position) {
//code
holder.textview. setCustomSelectionActionModeCallback(new CustomSelectionCallback(holder.taskName, position, mContext));
}
在自定义回调中,我们可以发送任何内容以及项目的位置。
自定义选择回调可以按如下方式实现。
public class CustomSelectionCallback implements ActionMode.Callback {
private TextView mTextView;
private int position;
private Context mContext;
public CustomSelectionCallback(TextView text, int pos, Context context) {
this.mTextView = text;
this.position = pos;
this.mContext = context;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int start = mTextView.getSelectionStart();
int end = mTextView.getSelectionEnd();
Spannable wordtoSpan = (Spannable) mTextView.getText();
wordtoSpan.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//copy the text when Copy Action Mode is clicked
if (item.getItemId() == android.R.id.copy) {
copyText(start, end);
mode.finish();
return true;
} else if (item.getItemId() == android.R.id.shareText) {
shareText(start, end);
mode.finish();
return true;
} else if (item.getItemId() == android.R.id.selectAll) {
selectAllText();
return true;
}
return true;
}
/**
* implement select all functionality id ActionMOde Menu
*/
private void selectAllText() {
Selection.setSelection((Spannable) mTextView.getText(), 0, mTextView.length());
}
private void shareText(int start, int end) {
CharSequence selectedTxt = mTextView.getText().subSequence(start, end);
String shareBody = selectedTxt.toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
mContext.startActivity(Intent.createChooser(sharingIntent, "SHARE"));
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
/**
* copy the selected text with start and end param to clipboard
*
* @param start start point of selection of the text view
* @param end end point of selection of the text view
*/
private void copyText(int start, int end) {
ClipboardManager clipboardManager = (ClipboardManager) mContext.
getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence selectedTxt = mTextView.getText().subSequence(start, end);
ClipData clipData = ClipData.newPlainText("selected text label", selectedTxt);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(mContext, selectedTxt.toString() + " position " + position, Toast.LENGTH_LONG).show();
}
}