Android如何在android中检测Edittext的Copy事件

时间:2014-07-11 12:02:05

标签: android events copy

我有一个我想要的Android应用程序:每当用户从edittext中按下复制时,任何事件都会发生,任何编辑文本就像来自messenger edittext,邮件edittext任何一个,当用户按复制文本时,我想发生任何事件,所以任何身体都给我这个例子吗?我不知道,所以请帮助我,提前谢谢。

2 个答案:

答案 0 :(得分:8)

我得到了解决方案: 我创建了一个服务: on oncreate:

         ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
         clipBoard.addPrimaryClipChangedListener(new ClipboardListener());

并添加服务:

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

    }
}

答案 1 :(得分:1)

通过使用EditText的以下代码,您可以获得剪切/复制/粘贴的事件。

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