ImageSpan not working on Android 5

孤街浪徒 提交于 2019-12-04 02:44:30

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.

<style name="Widget.Material.Button">
    <item name="background">@drawable/btn_default_material</item>
    <item name="textAppearance">?attr/textAppearanceButton</item>
    <item name="minHeight">48dip</item>
    <item name="minWidth">88dip</item>
    <item name="stateListAnimator">@anim/button_state_list_anim_material</item>
    <item name="focusable">true</item>
    <item name="clickable">true</item>
    <item name="gravity">center_vertical|center_horizontal</item>
</style>

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:

<style name="BtnStyle" parent="android:Widget.Material.Button">
    <item name="android:textAppearance">@null</item>
</style>

Then in your layout:

<Button
    android:id="@+id/test2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Test"
    style="@style/BtnStyle"/>

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

Shishram

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.

<Button
    ...
    android:textAllCaps="false" />

have a look here

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.

For Android 5.0+

Drawable getDrawable(int id) This method was deprecated in API level 22. Use getDrawable(int, Theme) instead.

Drawable getDrawable(int id, Resources.Theme theme) Return a drawable object associated with a particular resource ID and styled for the specified theme.

The second parameter looks like to be a Theme, not a color. right ?

try this

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      getResources().getDrawable(R.drawable.your_drawable, getTheme());
            } else {
                getResources().
                        getDrawable(R.drawable.your_drawable);
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!