Android禁止对密码输入框进行粘贴复制

  1. 一般手机对输入框禁止长按就可以禁止复制行为
    setLongClickable(false); //禁止长按 setTextIsSelectable(false); // 禁止被用户选择
  2. 但个别手机会出现粘贴选项框,要对输入框禁止粘贴,TextView.class中方法onTextContextMenuItem(int id)
    `
  /** * Called when a context menu option for the text view is selected.  Currently
 * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut},
 * {@link android.R.id#copy}, {@link android.R.id#paste} or {@link android.R.id#shareText}.
 * @return true if the context menu item action was performed.
 */  
 public boolean onTextContextMenuItem(int id){
     …………………………
     switch (id) {
        case ID_SELECT_ALL:
            selectAllText();
            return true;

        case ID_UNDO:
            if (mEditor != null) {
                mEditor.undo();
            }
            return true;  // Returns true even if nothing was undone.

        case ID_REDO:
            if (mEditor != null) {
                mEditor.redo();
            }
            return true;  // Returns true even if nothing was undone.

        case ID_PASTE:
            paste(min, max, true /* withFormatting */);
            return true;

        case ID_PASTE_AS_PLAIN_TEXT:
            paste(min, max, false /* withFormatting */);
            return true;

        case ID_CUT:
            setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
            deleteText_internal(min, max);
            return true;

        case ID_COPY:
            setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max)));
            stopTextActionMode();
            return true;

        case ID_REPLACE:
            if (mEditor != null) {
                mEditor.replace();
            }
            return true;

        case ID_SHARE:
            shareSelectedText();
            return true;
    }
    return false;
} 

EditText继承TextView,只要重写onTextContextMenuItem(int id)方法,对粘贴方法不做响应,即可实现不粘贴功能

  @Override
public boolean onTextContextMenuItem(int id) {
    if (id == android.R.id.paste) {
        return false;
    }
    return super.onTextContextMenuItem(id);
}  `

猜你喜欢

转载自blog.csdn.net/jiankeufo/article/details/81334745
今日推荐