Dalton
Dalton

Reputation: 447

Extracting words from TextView after click/press on them

is there any easy way to select whole words from TextView by touching them? This functionality is in dictionary app ColorDict.

  1. Search for word "word"
  2. Select word "theorem" and it now appears in the search box so I can search it faster by clicking on search.

I want to be able to select those words. That ScrollView which is on top is misleading. It appears after selecting "Select a word" in dialog which appears after long press on something in TextView (you can see word "theorem" on the bottom - long press on "theorem").

Thank you for suggestions.

Upvotes: 0

Views: 406

Answers (1)

jvincek
jvincek

Reputation: 580

Try setting this attribute to your TextView:

android:textIsSelectable="true"

EDIT:

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;
        }
    });
}

Upvotes: 1

Related Questions