Android how to detect Copy event of Edittext in android

主宰稳场 提交于 2019-12-18 03:44:03

问题


I have one android apps in that i want : whenever user press copy from the edittext,any event occure, it any of edittext like from messenger edittext,mail edittext any one,when user press copy text, i want to occure any event,so any body give me example for this ?i have no idea about it,so please help me, thanks in advance.


回答1:


I got solutions: I create one service : on that in oncreate :

         ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
         clipBoard.addPrimaryClipChangedListener(new ClipboardListener());

and add in service :

        class ClipboardListener implements
        ClipboardManager.OnPrimaryClipChangedListener {
        public void onPrimaryClipChanged() {
        ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        CharSequence pasteData = "";
        ClipData.Item item = clipBoard.getPrimaryClip().getItemAt(0);
        pasteData = item.getText();
        Toast.makeText(getApplicationContext(), "copied val=" + pasteData,
                Toast.LENGTH_SHORT).show();

    }
}



回答2:


By using the below code for EditText you can get the event for Cut/Copy/Paste.

public class EditTextMonitor extends EditText{
private final Context mcontext; // Just the constructors to create a new EditText...

public EditTextMonitor(Context context) {
    super(context);
    this.mcontext = context;
}

public EditTextMonitor(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.mcontext = context;
}

public EditTextMonitor(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.mcontext = context;
}


@Override
public boolean onTextContextMenuItem(int id) {
    // Do your thing:
    boolean consumed = super.onTextContextMenuItem(id);
    // React:
    switch (id){
        case android.R.id.cut:
            onTextCut();
            break;
        case android.R.id.paste:
            onTextPaste();
            break;
        case android.R.id.copy:
            onTextCopy();
    }
    return consumed;
}

/**
 * Text was cut from this EditText.
 */
public void onTextCut(){Toast.makeText(mcontext, "Event of Cut!", Toast.LENGTH_SHORT).show();
}

/**
 * Text was copied from this EditText.
 */
public void onTextCopy(){
    Toast.makeText(mcontext, "Event of Copy!", Toast.LENGTH_SHORT).show();
}

/**
 * Text was pasted into the EditText.
 */
public void onTextPaste(){
    Toast.makeText(mcontext, "Event of Paste!", Toast.LENGTH_SHORT).show();
}}


来源:https://stackoverflow.com/questions/24697236/android-how-to-detect-copy-event-of-edittext-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!