Mark Comix
Mark Comix

Reputation: 1898

How to add a Drawable next to button's text programmatically

I need to add an image right next to the button's text.

Using XML can I set the android:drawableEnd, but programmatically and for Api 10 I can't find the way.

I tryed with:

    button.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0);

    button.setPadding(0, 0, rightPadding, 0);

but that move the text to left. I want the imagen right next to the text.

There is any way?

Thanks and sorry for my poor english

Upvotes: 0

Views: 2408

Answers (2)

4gus71n
4gus71n

Reputation: 4073

You could use use a SpanneableString.

yourButtonView.text = SpannableString(" ${getString(R.string.your_string)}").apply {
     setSpan(
          ImageSpan(requireContext(), R.drawable.your_icon),
          0,
          1,
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
     )
}

Upvotes: 1

Bryan Herbst
Bryan Herbst

Reputation: 67189

The equivalent to android:drawableEnd is setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, id, 0).

The third argument to setCompoundDrawablesWithIntrinsicBounds() matches up with drawableRight, whereas the third argument to setCompoundDrawablesRelativeWithIntrinsicBounds() matches up with drawableEnd.

If you are trying to adjust the padding between the drawable and the text, you should use setCompoundDrawablePadding(int), not setPadding(). The latter adjusts padding for the TextView and the drawable as a whole, whereas the former will change the padding between the two.

Update: Unfortunately you cannot set a drawable to be drawn immediately after the text in a TextView (or Button). drawableRight will only set a drawable to be drawn on the far right side of the TextView. If you set your Button's width to wrap_content, it will appear where you want, but the button obviously won't be the right width.

The best solution in this case would probably be to create a RelativeLayout that contains an ImageView and a TextView. You can style the RelativeLayout to look like a button, and set your click listener on that.

Upvotes: 1

Related Questions