自定義EditText
長(zhǎng)按粘貼的監(jiān)聽以及修改
//重寫 onTextContextMenuItem方法
override fun onTextContextMenuItem(id: Int): Boolean {
if (id == R.id.paste) {
//調(diào)用剪貼板
val clip: ClipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clip.primaryClip?.let {
if (it.itemCount > 0) {
val input = it.getItemAt(0).coerceToText(context).toString().replace(" ", "")
//進(jìn)行判斷 是否需要修改剪貼板內(nèi)容
if (isPhone(input)) {//設(shè)置修改內(nèi)容
val clipData = ClipData.newPlainText(input, input)
clip.setPrimaryClip(clipData)
}
}
}
}
return super.onTextContextMenuItem(id)
}
輸入法上的快捷粘貼
輸入法和EditText通訊使用InputConnection
自定義InputConnectionWrapper
class InputConnection(
target: android.view.inputmethod.InputConnection?,
mutable: Boolean,
val changeText: (String) -> Boolean
) :
android.view.inputmethod.InputConnectionWrapper(
target, mutable
) {
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
val content = text.toString().replace(" ", "")
if (changeText.invoke(content)) {
//攔截并自己設(shè)置文案
return true
}
//true 攔截修改
return super.commitText(text, newCursorPosition)
}
}
全代碼
@SuppressLint("AppCompatCustomView")
class GoEditText(context: Context?, attrs: AttributeSet?) : EditText(context, attrs) {
override fun onTextContextMenuItem(id: Int): Boolean {
if (id == R.id.paste) {
//調(diào)用剪貼板
val clip: ClipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clip.primaryClip?.let {
if (it.itemCount > 0) {
val input = it.getItemAt(0).coerceToText(context).toString().replace(" ", "")
if (isPhone(input)) {
val clipData = ClipData.newPlainText(input, input)
clip.setPrimaryClip(clipData)
}
}
}
}
return super.onTextContextMenuItem(id)
}
private fun isPhone(text: String): Boolean {
val match = "0?(13|14|15|18)[0-9]{9}"
val pattern: Pattern = Pattern.compile(match)
val matcher: Matcher = pattern.matcher(text)
return matcher.matches()
}
val changeText: (String) -> Boolean = {
if (isPhone(it)) {
setText(it)
setSelection(it.length)
true
} else {
false
}
}
override fun onCreateInputConnection(outAttrs: EditorInfo?): InputConnection {
return InputConnection(super.onCreateInputConnection(outAttrs), false, changeText)
}
class InputConnection(
target: android.view.inputmethod.InputConnection?,
mutable: Boolean,
val changeText: (String) -> Boolean
) :
android.view.inputmethod.InputConnectionWrapper(
target, mutable
) {
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
val content = text.toString().replace(" ", "")
if (changeText.invoke(content)) {
return true
}
return super.commitText(text, newCursorPosition)
}
}
}