androideventspaste

How to detect the paste event in editext of the application?


How to detect when a user copies a data and paste it in the edittext of the application. Only need to detect the paste event.

For example: When a user copies the credit card details from a saved note in the phone and paste it in the corresponding edittext of application, how can we detect it, only the paste event?

Or is there any other solution is available for to solve this?


Solution

  • You can set Listener Class:

    public interface GoEditTextListener {
    void onUpdate();
    }
    

    Сreate self class for EditText:

    public class GoEditText extends EditText
    {
        ArrayList<GoEditTextListener> listeners;
    
        public GoEditText(Context context)
        {
            super(context);
            listeners = new ArrayList<>();
        }
    
        public GoEditText(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            listeners = new ArrayList<>();
        }
    
        public GoEditText(Context context, AttributeSet attrs, int defStyle)
        {
            super(context, attrs, defStyle);
            listeners = new ArrayList<>();
        }
    
        public void addListener(GoEditTextListener listener) {
            try {
                listeners.add(listener);
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Here you can catch paste, copy and cut events
         */
        @Override
        public boolean onTextContextMenuItem(int id) {
            boolean consumed = super.onTextContextMenuItem(id);
            switch (id){
                case android.R.id.cut:
                    onTextCut();
                    break;
                case android.R.id.paste:
                    onTextPaste();
                    break;
                case android.R.id.copy:
                    onTextCopy();
            }
            return consumed;
        }
    
        public void onTextCut(){
        }
    
        public void onTextCopy(){
        }
    
        /**
         * adding listener for Paste for example
         */
        public void onTextPaste(){
            for (GoEditTextListener listener : listeners) {
                listener.onUpdate();
            }
        }
    }
    

    xml:

    <com.yourname.project.GoEditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/editText1"/>
    

    And in your activity:

    private GoEditText editText1;
    
    editText1 = (GoEditText) findViewById(R.id.editText1);
    
                editText1.addListener(new GoEditTextListener() {
                    @Override
                    public void onUpdate() {
    //here do what you want when text Pasted
                    }
                });