如何在android EditText中禁用粘贴选项

时间:2014-04-16 05:26:34

标签: android android-edittext

我要求EditText不允许粘贴,但应允许复制。  我尝试了setCustomSelectionActionModeCallback,但它禁用了复制选项。

EditText  etxt = (EditText) findViewById(R.id.editText1);
etxt.setCustomSelectionActionModeCallback(new Callback() {

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {                  
            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });

3 个答案:

答案 0 :(得分:0)

如果您使用的是API等级11或以上,请使用此

      edittext.setCustomSelectionActionModeCallback(new Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {                  
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });

答案 1 :(得分:0)

我完成了自我..信用证转到Android intercept paste\copy\cut on editText

我刚刚根据我的要求更改了onTextContextMenuItem()..

@Override
    public boolean onTextContextMenuItem(int id) {
        // Do your thing:
        //boolean consumed = super.onTextContextMenuItem(id); // Change1
        // React:
        switch (id){
            case android.R.id.cut:
                onTextCut();
                break;
            case android.R.id.paste:
                onTextPaste();
                return false;       //Change2
                //break;
            case android.R.id.copy:
                onTextCopy();
        }
        return true; // Change3
    }

答案 2 :(得分:0)

如果你只想禁用粘贴选项,我认为最好删除paste context menu项,这是我在我的应用程序中实现的util方法(我也删除了剪切项)

    public static void toggleContextMenuType(EditText editText) {

    if (editText.getCustomSelectionActionModeCallback() == null) {
        editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                menu.removeItem(16908322);
                menu.removeItem(16908320);
                return true;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
            }
        });
    }else{
        editText.setCustomSelectionActionModeCallback(null);
    }
}