需求:在开头显示一个 @xxxx ,不可选中,不可删除
网上有很多复杂的,我这里不需要,看了下,主要是一个继承关系才能监听到光标没什么其他特别的,完整代码如下:
class AtEditText(context: Context, attrs: AttributeSet?) : AppCompatEditText(context, attrs) { private var userText: String? = "" fun init(userText: String, onLengthChange: (Int) -> Unit) { this.userText = userText setText(userText) setSelection(userText.length) addTextChangedListener { val curLength = text?.length ?: 0 if (curLength < userText.length) { setText(userText) setSelection(userText.length) } val i = (curLength - userText.length).coerceAtLeast(0) onLengthChange.invoke(i) } } override fun onSelectionChanged(selStart: Int, selEnd: Int) { val length = userText?.length ?: 0 if (selStart < length) { setSelection(length) super.onSelectionChanged(length, length) } else { super.onSelectionChanged(selStart, selEnd) } } }
本站由以下主机服务商提供服务支持:
归零幻想
还是应该保留单个参数的构造函数,否则在xml中使用可能会崩掉