ImageSpan不工作在Android上5 [英] ImageSpan not working on Android 5
问题描述
我有这个功能在Android 4.4.1工作正常,但休息的5.0+。
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;
}
和我使用这样的:
class MyButton extends Button {
// ... snip ...
setText(
prependImage(
getDrawable(imageResource, color),
getContext().getString(stringResource)),
BufferType.SPANNABLE);
下面是上面提到的 getDrawable()
方法:
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?
推荐答案
您code涉及与Spannables的工作就可以了。您可以通过设置文字的TextView检查。
Your code related to working with Spannables is ok. You can check it by setting text for TextView.
现在的问题是在按钮上的Android 5.0材料设计。
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>
有两种解决方案。
第一种是只使用的TextView 作为您的按钮,用的setText形象吧。
The first one is just use TextView as your button and setText with image to it.
有关另一个(并且可能更正确的),你需要扩展按钮样式( Widget.Material.Button
)的下一个方法:
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.
不要忘了为Android版本低于5.0,你应该创建 BtnStyle
过,但在其他资源目录(RES /值-V14 / style.xml)
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).
这篇关于ImageSpan不工作在Android上5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!