安卓粘贴事件

11

在我的应用程序中,有没有一种方法能够捕获粘贴事件?当我长按editText并从上下文菜单选择“粘贴”时,我必须执行某些操作。谢谢。

6个回答

5

创建position为'paste'的menu.xml文件

将contextMenu注册到您的EditText中

EditText et=(EditText)findViewById(R.id.et);
registerForContextMenu(et);

创建右键菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);    
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;  
    menu.setHeaderTitle("title");
}

创建 onClick 方法菜单

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();     
    switch (item.getItemId()) {
    case R.id.paste:      
        break;     
    }
    return true;
}

10
我知道这个帖子很旧了,但是这会用你自己的上下文菜单替换内置的上下文菜单吗?如果你喜欢那个菜单,只是想在粘贴发生时得到通知怎么办? - SMBiggs
@ScottBiggs 在不重新创建菜单的情况下也可以工作。请参见我的答案这里 - Lukas Knuth
请也看一下我的问题:https://stackoverflow.com/q/76520789/4134215 - Taimoor Khan

3

您应该在接收粘贴操作的控件上实现一个TextWatcher监听器。

TextWatcher类提供了处理任何可编辑文本的OnChange、BeforeChange和AfterChange的方法。例如:

private void pasteEventHandler() {
    ((EditText)findViewById(R.id.txtOutput))
            .addTextChangedListener(new TextWatcher() {

                public void afterTextChanged(Editable s) {
                    Log.d(TAG, "Text changed, refreshing view.");
                    refreshView();
                }

                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                }
            });
}

2
只是一个吹毛求疵的评论:将其转换为TextView就足够了。 - Tom anMoney
7
在我看来,这并没有回答用户的问题。 有了这个,你将会听到打字、删除、粘贴等操作。 - tiagocarvalho92

2
以下是代码,您可以覆盖操作栏的复制/粘贴等功能。
public class MainActivity extends Activity {
    EditText editText;
    private ClipboardManager myClipboard;
    private ClipData myClip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        editText = (EditText) findViewById(R.id.editText3);

        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        editText = (EditText) findViewById(R.id.editText3);
        editText.setCustomSelectionActionModeCallback(new Callback() {

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // TODO Auto-generated method stub
                switch (item.getItemId()) {
                case android.R.id.copy:
                    int min = 0;
                    int max = editText.getText().length();
                    if (editText.isFocused()) {
                        final int selStart = editText.getSelectionStart();
                        final int selEnd = editText.getSelectionEnd();

                        min = Math.max(0, Math.min(selStart, selEnd));
                        max = Math.max(0, Math.max(selStart, selEnd));
                    }
                    // Perform your definition lookup with the selected text
                    final CharSequence selectedText = editText.getText()
                            .subSequence(min, max);
                    String text = selectedText.toString();

                    myClip = ClipData.newPlainText("text", text);
                    myClipboard.setPrimaryClip(myClip);
                    Toast.makeText(getApplicationContext(), "Text Copied",
                            Toast.LENGTH_SHORT).show();
                    // Finish and close the ActionMode
                    mode.finish();
                    return true;
                case android.R.id.cut:
                    // add your custom code to get cut functionality according
                    // to your requirement
                    return true;
                case android.R.id.paste:
                    // add your custom code to get paste functionality according
                    // to your requirement
                    return true;

                default:
                    break;
                }
                return false;
            }
        });         
    }    
}

1
您可以使用我最近创建的这段代码。
        setOnReceiveContentListener(editText, arrayOf("text/*"),
        OnReceiveContentListener { view, payload ->
            if(view == editText && payload.source == ContentInfoCompat.SOURCE_CLIPBOARD && payload.clip.description.hasMimeType("text/*")) {
                var t=""
                for (i in 0 until payload.clip.itemCount) {
                    t += payload.clip.getItemAt(i).text
                }
                //do what ever you want to do with the text and set it to editText
                editText.setText(t)
                return@OnReceiveContentListener null
            } else
                return@OnReceiveContentListener payload
        }
    )

如果不是文本并且从剪贴板中复制,为避免任何意外拦截,请将有效载荷以原样返回。

1

在onActionItemClicked(mode: ActionMode, item: MenuItem)中收到了粘贴事件的回调

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        editText.customInsertionActionModeCallback = object : ActionMode.Callback {
            override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
                Log.e("ActionMode", "::ItemClicked")
                if(item?.groupId == android.R.id.paste){
                    Log.e("ActionMode", "::Paste::ItemClicked")
                }
                return true
            }

            override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
                Log.e("ActionMode", "::Created")
                return true
            }

            override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
                Log.e("ActionMode", "::Prepared")
                return true
            }

            override fun onDestroyActionMode(mode: ActionMode?) {
                Log.e("ActionMode", "::Destroyed")
            }

        }
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接