【问题标题】:Setting icon for TextInputLayout helper text and centering it to top设置 TextInputLayout 辅助文本的图标并将其居中放置在顶部
【发布时间】:2021-07-14 16:36:02
【问题描述】:

所以我需要设置两件事:

  1. TextInputLayout 中帮助文本的图标
  2. 居中于 TOP,因为帮助文本可能是多行的

它可能看起来像这样:

不制作自己的 TextInputLayout 是否可以轻松解决这个问题?

【问题讨论】:

    标签: android kotlin material-components-android android-textinputlayout


    【解决方案1】:

    解决这个问题可以归结为以下两种可能的解决方案:

    首先是通过设置边界(坐标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
                    )
                }
            }
        }
    }
    

    【讨论】:

    • 我很惊讶 Android 没有提供这样一种方法来设置帮助文本图标,这​​听起来像是某些项目中的常见需求。这个解决方案看起来很hacky...
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 2013-06-26
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2021-07-01
    • 2015-05-27
    相关资源
    最近更新 更多