美文网首页小技巧,大智慧小技巧Android知识
Android 禁止输入框 EditText 复制粘贴

Android 禁止输入框 EditText 复制粘贴

作者: simpleeeeee | 来源:发表于2017-04-20 10:53 被阅读538次

实现 EditText 禁止复制粘贴菜单

  • 禁止长按事件
  • ActionMode 回调
  • 反射 android.widget.Editor 修改弹框菜单不显示
/**
 * 禁止输入框复制粘贴菜单
 */
public void disableCopyAndPaste(final EditText editText) {
    try {
        if (editText == null) {
            return ;
        }

        editText.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        editText.setLongClickable(false);
        editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // setInsertionDisabled when user touches the view
                    setInsertionDisabled(editText);
                }

                return false;
            }
        });
        editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

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

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

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void setInsertionDisabled(EditText editText) {
    try {
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editorObject = editorField.get(editText);

        // if this view supports insertion handles
        Class editorClass = Class.forName("android.widget.Editor");
        Field mInsertionControllerEnabledField = editorClass.getDeclaredField("mInsertionControllerEnabled");
        mInsertionControllerEnabledField.setAccessible(true);
        mInsertionControllerEnabledField.set(editorObject, false);

        // if this view supports selection handles
        Field mSelectionControllerEnabledField = editorClass.getDeclaredField("mSelectionControllerEnabled");
        mSelectionControllerEnabledField.setAccessible(true);
        mSelectionControllerEnabledField.set(editorObject, false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Disable EditText context menu

相关文章

网友评论

    本文标题:Android 禁止输入框 EditText 复制粘贴

    本文链接:https://www.haomeiwen.com/subject/lmnkzttx.html