我的这个功能在Android4.4.1上运行得很好,但在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()方法:
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;
}当我调试时,一切似乎都成功了,但没有绘制任何图像。知道我可能做错了什么吗?
发布于 2015-09-30 07:42:44
您的代码与使用Spannable相关的代码是可以的。您可以通过设置TextView文本来检查它。
问题是在Android5.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。
另一方面(而且可能更正确),您需要以下一种方式扩展按钮样式(Widget.Material.Button):
<style name="BtnStyle" parent="android:Widget.Material.Button">
<item name="android:textAppearance">@null</item>
</style>然后在你的布局中:
<Button
android:id="@+id/test2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test"
style="@style/BtnStyle"/>在你做完之后,你应该看到按钮中的图像。
不要忘记,对于低于5.0的Android版本,您也应该创建BtnStyle,但是在其他资源目录中(res/values v14/style.xml)。
发布于 2015-09-30 13:19:57
默认情况下,材料按钮的样式是以全大写显示文本.但是,用于大写化的AllCapsTransformationMethod中存在一个错误,导致它丢弃可扩展数据。
您可以通过在按钮上指定android:textAllCaps="false“来覆盖默认按钮样式和禁用所有大写。
<Button
...
android:textAllCaps="false" />看一看这里
发布于 2020-08-10 10:26:09
需要注意的一点是,可绘制向量不能工作,您必须有一个可绘制的,即png或jpeg,或者传递给ImageSpan位图。
https://stackoverflow.com/questions/32257606
复制相似问题