Kotlin中点击EditText时移除键盘剪贴板选项的实现方法
Android 移除EditText键盘剪贴板选项并禁止第三方粘贴
需求:点击EditText时移除键盘上的剪贴板选项,同时禁止从第三方应用粘贴数据。
现有尝试代码问题分析
你之前尝试的代码仅在粘贴后清空文本,并未真正拦截粘贴操作,也没有处理键盘上的剪贴板选项,无法达到预期效果:
override fun onTextContextMenuItem(id: Int): Boolean { val consumed = super.onTextContextMenuItem(id) when (id) { R.id.cut -> onTextCut() R.id.paste -> onTextPaste() R.id.copy -> onTextCopy() } return consumed } fun onTextCut() {} fun onTextCopy() {} fun onTextPaste() { text?.clear() }
解决方案
方案一:自定义EditText(推荐,复用性强)
通过自定义EditText,从上下文菜单和输入法连接两个层面彻底禁用粘贴并移除键盘剪贴板选项:
class NoPasteEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.editTextStyle ) : AppCompatEditText(context, attrs, defStyleAttr) { // 拦截上下文菜单中的剪切、复制、粘贴操作 override fun onTextContextMenuItem(id: Int): Boolean { return when (id) { android.R.id.cut, android.R.id.copy, android.R.id.paste -> true // 返回true表示已处理,不执行默认操作 else -> super.onTextContextMenuItem(id) } } // 处理输入法连接,移除剪贴板选项并拦截粘贴 override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { val inputConnection = super.onCreateInputConnection(outAttrs) // 移除键盘上的剪贴板预览/选项 outAttrs.imeOptions = outAttrs.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI return object : InputConnectionWrapper(inputConnection, true) { // 拦截粘贴操作 override fun performContextMenuAction(id: Int): Boolean { return when (id) { android.R.id.paste -> true else -> super.performContextMenuAction(id) } } } } }
使用时直接在布局文件中引用这个自定义EditText即可。
方案二:直接修改现有EditText
如果不想自定义控件,可通过以下代码快速改造现有EditText:
// 阻止长按弹出上下文菜单 editText.setOnLongClickListener { true } // 移除上下文菜单中的复制/粘贴选项 editText.customSelectionActionModeCallback = object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { menu?.apply { removeItem(android.R.id.cut) removeItem(android.R.id.copy) removeItem(android.R.id.paste) } return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { menu?.apply { removeItem(android.R.id.cut) removeItem(android.R.id.copy) removeItem(android.R.id.paste) } return true } override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean = false override fun onDestroyActionMode(mode: ActionMode?) {} } // 移除键盘剪贴板选项并拦截粘贴 val editorInfo = EditorInfo() val inputConnection = editText.onCreateInputConnection(editorInfo) editorInfo.imeOptions = editorInfo.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI val wrappedInputConnection = object : InputConnectionWrapper(inputConnection, true) { override fun performContextMenuAction(id: Int): Boolean { return when (id) { android.R.id.paste -> true else -> super.performContextMenuAction(id) } } }
内容的提问来源于stack exchange,提问作者D.J
相关产品推荐
相关产品推荐

