I have this function that works fine on Android 4.4.1, but breaks on 5.0+.
public static SpannableStringBuilder prependImage(Drawable drawable, String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(" " + text);
builder.setSpan(new ImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return builder;
}
And I use it like this:
class MyButton extends Button {
// ... snip ...
setText(
prependImage(
getDrawable(imageResource, color),
getContext().getString(stringResource)),
BufferType.SPANNABLE);
Here is the getDrawable()
method referenced above:
private Drawable getDrawable(int resource, int color) {
final Resources resources = getContext().getResources();
Drawable drawable = resources.getDrawable(resource);
if (drawable != null) {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
When I debug, everything seems to succeed, but no image is drawn. Any ideas what I might be doing wrong?
try this
Maybe you need to check the content of that Drawable object, you use the getDrawable() to get the Drawable object, but the API definition seems not match your calling parameters.
The second parameter looks like to be a Theme, not a color. right ?
By default, in Material buttons are styled to show text in all-caps. However, there is a bug in the AllCapsTransformationMethod used for capitalization that causes it to discard Spannable data.
You can override the default button styling and disable all-caps by specifying android:textAllCaps="false" on your Button.
have a look here
Your code related to working with Spannables is ok. You can check it by setting text for TextView.
The problem is in material design of button on Android 5.0.
There are two solution.
The first one is just use TextView as your button and setText with image to it.
For another (and may be more correct) you need to extend button style (
Widget.Material.Button
) in next way:Then in your layout:
After you'll do it you should see the images in the button.
Don't forget for Android version that is lower than 5.0 you should create
BtnStyle
too, but in other resource directory (res/values-v14/style.xml).