利用Kotlin 擴(kuò)展函數(shù),為EditText增加 “禁用復(fù)制粘貼” 功能
**
* @author: ChenXi
* @create_time: 2022/6/29 11:47
* @class_desc: 實(shí)現(xiàn)禁用 EditText 復(fù)制和粘貼 功能
* @remarks: Java調(diào)用舉例: EditTextUtilKt.disableCopy(et_account);
*/
@JvmOverloads
fun EditText.disableCopy(disablePaste: Boolean = true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val callback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
//創(chuàng)建菜單項ActionMode,返回false表示不創(chuàng)建,事件結(jié)束
return false
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
//菜單項更新,返回false表示沒有更新,事件結(jié)束
return false
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
//選擇菜單項的某一項,返回true表示攔截點(diǎn)擊事件,事件結(jié)束
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
//菜單項ActionMode銷毀,什么也不做
}
}
//禁用復(fù)制
this.customSelectionActionModeCallback = callback
//禁用粘貼
if (disablePaste)
this.customInsertionActionModeCallback = callback
} else {
//通過反射來禁用復(fù)制和粘貼
disableCopyAndPasteByReflect(disablePaste)
}
}
private fun EditText.disableCopyAndPasteByReflect(disablePaste: Boolean) {
try {
//因?yàn)镋ditor包含兩個boolean字段: mInsertionControllerEnabled、mSelectionControllerEnabled,
// 其中mInsertionControllerEnabled表示粘貼,為false就不起作用
// 其中mSelectionControllerEnabled表示選中文本,為false就不起作用
//所以,獲取Editor之后,將這兩個boolean字段設(shè)為false就可以禁用復(fù)制和粘貼
//1、獲取EditText的Editor實(shí)例
val editorField = TextView::class.java.getDeclaredField("mEditor")
editorField.isAccessible = true
val editorInstance = editorField.get(this)
val editorClass = Class.forName("android.widget.Editor")
//2、獲取Editor的mSelectionControllerEnabled字段,設(shè)為false禁用復(fù)制
val selectField = editorClass.getDeclaredField("mSelectionControllerEnabled")
selectField.isAccessible = true
selectField.set(editorInstance, false)
//3、獲取Editor的mInsertionControllerEnabled字段,設(shè)為false禁用粘貼
if (disablePaste) {
val insertField = editorClass.getDeclaredField("mInsertionControllerEnabled")
insertField.isAccessible = true
insertField.set(editorInstance, false)
}
} catch (e: Exception) {
LogUtil.e("in EditText.disableCopyAndPasteByReflect() : ", e)
}
}