【发布时间】:2015-07-25 17:23:39
【问题描述】:
我尝试为每个单词显示一个带有“chips”样式的 TextView。 换句话说,我想让这个Splitwise TokenAutoComplete 不可编辑也不自动完成。
所以我有一个适合我风格的drawable:
muscle_token_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/primary_dark" />
<corners
android:topLeftRadius="5dp"
android:bottomLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomRightRadius="5dp" />
</shape>
我有我的风格,使用可绘制:
themes.xml
<resources>
<style>
.....
</style>
<style name="textview_chips" parent="@android:style/TextAppearance.Medium">
<item name="android:background">@drawable/muscle_token_background</item>
</style>
</resources>
我找到的解决方案是使用 SpannableStringBuilder 和 SyleSpan :
SpannableStringBuilder sb = new SpannableStringBuilder(myString);
int currentCharCount = sb.length();
sb.append(myString.trim());
int nextCharCount = sb.length();
sb.setSpan(new StyleSpan(R.style.textview_chips), currentCharCount, nextCharCount, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(sb);
但 TextView 只会变成斜体。
我尝试在 XML 文件中使用另一个 TextView,并且背景可绘制对象显示良好
<TextView
...
style="@style/textview_chips"
... />
那么我该如何为 TextView 的每个单词应用这种样式呢?
【问题讨论】:
-
StyleSpan不适用于应用您在styles.xml中定义的样式资源。它用于使文本变为粗体、斜体、粗体和斜体,或正常。构造函数需要在Typeface类中定义的值,这些值对应于粗体/斜体/等状态。根据您想要的背景,可能会有不同类型的 span 可以使用(例如BackgroundColorSpan),但您必须提供更多信息。
标签: android textview spannablestring android-chips