[英]Why does adding an ImageSpan to a Snackbar's action text work on Android devices SDK level 26 but not on SDK level 25?
I want to show a Snackbar
and use an image instead of text for the action.我想显示一个Snackbar
并使用图像而不是文本进行操作。
I use the following code:我使用以下代码:
val imageSpan = ImageSpan(this, R.drawable.star)
val builder = SpannableStringBuilder(" ")
builder.setSpan(
imageSpan,
0,
1,
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
)
Snackbar.make(findViewById(R.id.container), "Hello Snackbar", Snackbar.LENGTH_INDEFINITE)
.setAction(builder) {}.show()
drawable_star
being a vector graphic asset, but the same happens with a png
. drawable_star
是矢量图形资源,但png
也是如此。
On an Android device lvl 26 and above this yields:在 Android 设备 lvl 26 及以上,这会产生:
as expected, whereas on device lvl 25 the image is not visible:正如预期的那样,而在设备 lvl 25 上,图像不可见:
Does someone know the reason for this and if there a workaround?有人知道原因以及是否有解决方法吗?
PS: You can check out my test project here: https://github.com/fmweigl/SpannableTest PS:你可以在这里查看我的测试项目: https://github.com/fmweigl/SpannableTest
That's due to the textAllCaps
bug on versions prior to Oreo.这是由于 Oreo 之前版本的textAllCaps
错误造成的。 That Button
's default style will have that attribute set to true
, which simply causes the Button
's text to be converted to all uppercase.该Button
的默认样式将该属性设置为true
,这只会导致Button
的文本全部转换为大写。 That conversion is done with the platform AllCapsTransformationMethod
class, which, on Nougat 7.1 and below, would treat everything as flat String
s, essentially stripping any formatting spans you've set.该转换是使用平台AllCapsTransformationMethod
class 完成的,在 Nougat 7.1 及更低版本上,该平台会将所有内容都视为平面String
s,基本上会剥离您设置的任何格式跨度。
The fix is to turn that attribute off, and handle any uppercase conversion you might need yourself, in code.解决方法是关闭该属性,并在代码中处理您自己可能需要的任何大写转换。 Snackbar
offers the snackbarButtonStyle
attribute as a means to style the action Button
, and we can create a simple style to modify that value. Snackbar
提供了snackbarButtonStyle
属性作为设置动作Button
样式的方法,我们可以创建一个简单的样式来修改该值。 For example, from your styles.xml
:例如,从您的styles.xml
:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="snackbarButtonStyle">@style/NoCapsButton</item>>
</style>
<style name="NoCapsButton" parent="Widget.AppCompat.Button">
<item name="textAllCaps">false</item>
</style>
(If you're using a Material Components theme, the parent
for NoCapsButton
should instead be Widget.MaterialComponents.Button.TextButton.Snackbar
.) (如果您使用的是 Material Components 主题,则NoCapsButton
的parent
级应该是Widget.MaterialComponents.Button.TextButton.Snackbar
。)
In this specific case, that's all you need to do, since there's no text to convert.在这种特定情况下,这就是您需要做的所有事情,因为没有要转换的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.