How can i display a toast message in the clipboard copy option click in android

3.9k views Asked by At

In my fragment I used one layout. In that, for one textview I need to provide the copy option.

<TextView
                    android:id="@+id/txtShareWinurl"
                    style="@style/matchWidth"
                    android:layout_height="@dimen/dimen_fifty"
                    android:layout_gravity="center"
                    android:layout_margin="@dimen/dimen_ten"
                    android:background="@drawable/verylight_gray_bg_border"
                    android:gravity="center"
                    android:padding="@dimen/dimen_five"
                    android:text="@string/app_name"
                    android:textColor="@color/gray_code"
                    android:textSize="@dimen/dimen_fifteen"
                    android:textIsSelectable="true"
                    android:textStyle="bold" />

In that I used textIsSelectable than i got the window with copy and selectall options. But when i click on that option i need to display a toast. Please help me.

I tried and google some links but I didn't succeed.

3

There are 3 answers

1
Christian On

It depends on your scenario, but you can detect the clipboard-change with ClipboardManager:

ClipbardManager Documenation

Example code:

ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
    @Override
    public void onPrimaryClipChanged() {
        Toast.makeText(MainActivity.this, "Content changed", Toast.LENGTH_LONG).show();
    }
});
0
chiragjn On

Check this out

You can override ClipboardManager's onPrimaryClipChanged() Listner

0
rus1f1kat0R On

The only way I know is to use ActionMode.Callback interface

private class ActionModeCallbackWrapper implements ActionMode.Callback {
    private final ActionMode.Callback wrapped;

    private ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        return wrapped.onCreateActionMode(mode, menu);
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return wrapped.onPrepareActionMode(mode, menu);
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return wrapped.onActionItemClicked(mode, item);
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        wrapped.onDestroyActionMode(mode);
    }
}

And use it in your view like the following (docs)

@Override
public ActionMode startActionMode(ActionMode.Callback callback) {
    mActionMode = super.startActionMode(new ActionModeCallbackWrapper(callback));
    return mActionMode;
}

So you can detect onActionItemClicked event and show toast or whatever you want