如何检测应用程序编辑文本中的粘贴事件?

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

如何检测用户何时复制数据并将其粘贴到应用程序的编辑文本中。只需要检测粘贴事件。

例如:当用户从phone中保存的笔记中复制信用卡详细信息并将其粘贴到应用程序相应的edittext中时,我们如何检测到它,只有粘贴事件?

或者是否有其他解决方案可以解决这个问题?

您可以设置监听器Class:

public interface GoEditTextListener {
void onUpdate();
}

为 EditText 创建自我 class:

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"/>

在你的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
                }
            });