模仿小红书,用kotlin写一个适用于安卓的EditView
时间: 2024-04-30 13:17:25 浏览: 9
好的,我明白了。关于您提出的问题,我可以为您提供以下代码:
```
class RedBookEditView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : EditText(context, attrs, defStyleAttr) {
private var delegate: RedBookDelegate? = null
private var hintTextView: TextView? = null
init {
initAttrs(context, attrs, defStyleAttr)
initView()
}
private fun initAttrs(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.RedBookEditView, defStyleAttr, 0)
val hintResId = ta.getResourceId(R.styleable.RedBookEditView_rbev_hint, 0)
hintTextView = TextView(context)
hintTextView!!.setTextColor(resources.getColor(R.color.hint_text_color))
hintTextView!!.textSize = 14f
hintTextView!!.text = resources.getText(hintResId)
addView(hintTextView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
ta.recycle()
}
private fun initView() {
delegate = RedBookDelegate(this)
hintTextView!!.setOnClickListener {
setSelection(length())
requestFocus()
}
setOnFocusChangeListener { _, hasFocus ->
delegate!!.setFocus(hasFocus)
if (hasFocus) {
hintTextView!!.visibility = View.GONE
} else {
hintTextView!!.visibility = View.VISIBLE
}
}
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
delegate!!.handleTextChanged(s)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
delegate!!.handleTextChangedBefore(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
delegate!!.handleTextChangedOn(s, start, before, count)
}
})
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val hintTextViewWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth - paddingLeft - paddingRight, MeasureSpec.EXACTLY)
val hintTextViewHeightMeasureSpec = MeasureSpec.makeMeasureSpec(measuredHeight - paddingTop - paddingBottom, MeasureSpec.EXACTLY)
hintTextView!!.measure(hintTextViewWidthMeasureSpec, hintTextViewHeightMeasureSpec)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (text.isNullOrEmpty()) {
hintTextView!!.visibility = View.VISIBLE
} else {
hintTextView!!.visibility = View.GONE
}
}
}
```
这是一个 `EditText` 的子类,主要实现了类似小红书的 hint 文字效果,当输入框没有内容时,在输入框内自动显示灰色的提示文字。同时,为了加强体验,还重载了 `onFocusChanged` 和 `onDraw` 方法,当输入框获得/失去焦点时,隐藏/显示提示文字。
我希望这个代码能够对您有所帮助!