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

前端 未结 1 1914
孤城傲影
孤城傲影 2020-12-16 04:59

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 c

相关标签:
1条回答
  • 2020-12-16 05:25

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