Setting icon for TextInputLayout helper text and centering it to top

Viewed 307

So I need to set up 2 things:

  1. Icon for helper text in TextInputLayout
  2. Center it to TOP, since helper text might be multiline

It might look something like this:

enter image description here

Is there easy of doing working around this, without making my own TextInputLayout?

1 Answers

Solving this melts down to following 2 possible solutions:

First is to change the Rect of the Drawable itself by setting the bounds (coordinates X and Y), drawback of this solution is whenever layout is redrawn (orientation change etc.), this has to be done again.

        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)
            }
        }

Second solution is to add new ImageView in front of the helper TextView and add padding to it, so it's pushed up. It's not a one liner, but it can be formed into easy to use method as such:

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
                )
            }
        }
    }
}
Related