0

一个简单的 EditText @评论框

 1 year ago
source link: http://i.lckiss.com/?p=8269
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个简单的 EditText @评论框

抬头仰望星空,是否能发现自己的渺小。

伪斜杠青年

一个简单的 EditText @评论框

2023-08-01

需求:在开头显示一个 @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)
        }
    }
}

本站由以下主机服务商提供服务支持:

作者:Mosaic-C

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK