試試這個屬性設置爲你的TextView
:
android:textIsSelectable="true"
編輯:
private static final int MENU_ITEM_ID = 0x42;
private TextView targetTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetTextView = (TextView) findViewById(R.id.target_textview);
targetTextView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// you can remove the default menu items if you wish
menu.removeItem(android.R.id.selectAll);
menu.removeItem(android.R.id.cut);
menu.removeItem(android.R.id.copy);
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
/*
* called when the action mode is created. Here you can
* generate action buttons for this action mode.
* */
menu.add(0, MENU_ITEM_ID, 0, "Menu Item").setIcon(android.R.drawable.ic_dialog_alert);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// called when the action mode is about to be destroyed
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_ID:
int start = targetTextView.getSelectionStart();
int end = targetTextView.getSelectionEnd();
CharSequence selectedText = targetTextView.getText().subSequence(start, end);
Toast.makeText(MainActivity.this, selectedText, Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
break;
}
return false;
}
});
}
好吧,以及如何使其短按後選擇整個單詞?如何在短時間按下單詞後觸發某些內容?有一些處理程序? – dalton
我已經添加了示例代碼來啓用此功能。但是,請注意,這是API級別11的可用性。我不確定如何爲早期Android版本執行此操作。 – jvincek
這是否解決了您的問題?如果是,請將此答案標記爲已接受。如果沒有,請提供有關這些問題的更多信息。 – jvincek