Android how to detect Copy event of Edittext in android

前端 未结 2 1360
广开言路
广开言路 2020-12-16 06:59

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,w

相关标签:
2条回答
  • 2020-12-16 07:36

    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();
    }}
    
    0 讨论(0)
  • 2020-12-16 07:53

    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();
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题