【发布时间】:2021-07-14 16:36:02
【问题描述】:
所以我需要设置两件事:
- TextInputLayout 中帮助文本的图标
- 居中于 TOP,因为帮助文本可能是多行的
它可能看起来像这样:
不制作自己的 TextInputLayout 是否可以轻松解决这个问题?
【问题讨论】:
标签: android kotlin material-components-android android-textinputlayout
所以我需要设置两件事:
它可能看起来像这样:
不制作自己的 TextInputLayout 是否可以轻松解决这个问题?
【问题讨论】:
标签: android kotlin material-components-android android-textinputlayout
解决这个问题可以归结为以下两种可能的解决方案:
首先是通过设置边界(坐标X和Y)来改变Drawable本身的Rect,这个解决方案的缺点是每当重新绘制布局(方向改变等),这必须再做一次。
findViewById<AppCompatTextView>(R.id.textinput_helper_text)?.run {
compoundDrawables.first()?.run {
setBounds(
bounds.left,
bounds.top - this@with.height.div(2),
bounds.right,
bounds.bottom - this@with.height.div(2)
)
bottom = this@with.height.div(2)
}
}
第二种解决方法是在helper TextView前面添加新的ImageView,并在其中添加padding,这样就被推上去了。
它不是一个单一的衬垫,但它可以形成易于使用的方法:
fun TextInputLayout.setStartHelperTextIcon(
@DrawableRes drawableRes: Int,
paddingPx: Int
) {
with(findViewById<AppCompatTextView>(R.id.textinput_helper_text)) {
(this?.parent?.parent as? LinearLayout)?.run {
if(findViewById<ImageView>(R.id.text_input_layout_helper_icon) == null) {
addView(
ImageView(context).apply {
id = R.id.text_input_layout_helper_icon
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setPadding(
paddingPx,
0,
paddingPx,
paddingPx + this@with.height.div(2)
)
},
0
)
}
}
}
}
【讨论】: