【问题标题】:How to detect the paste event in editext of the application?如何检测应用程序editext中的粘贴事件?
【发布时间】:2015-07-28 05:30:14
【问题描述】:

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

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

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

【问题讨论】:

标签: android events paste


【解决方案1】:

你可以设置监听类:

public interface GoEditTextListener {
void onUpdate();
}

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

在你的活动中:

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
                }
            });

【讨论】:

  • 如何查看要粘贴的内容?
  • @jonney 您可以为侦听器事件赋值,或者在 onUpdate 事件中从 EditText 获取它
  • 仅供参考 此解决方案仅在用户长按edittext然后按粘贴弹出菜单时有效。但是如果设备键盘在建议框中将复制的文本显示给用户,并允许用户点击它来粘贴文本,那么上述解决方案将不起作用。
猜你喜欢
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多