如何在Android TextView上实现这样的效果。它看起来有点像选定的文本,但我在API中找不到类似的东西。
这不是视图的背景颜色,而是仅用于文本的背景颜色。您可以看到它在换行处停止,并且在文本行之间有一条细白线。
如何在Android TextView上实现这样的效果。它看起来有点像选定的文本,但我在API中找不到类似的东西。
这不是视图的背景颜色,而是仅用于文本的背景颜色。您可以看到它在换行处停止,并且在文本行之间有一条细白线。
<TextView
android:background="#0000FF"
android:textColor="#FFFFFF" />
您想定义一个背景为蓝色、文字为白色的 TextView
...这符合您的需要吗?
我相信实现这个的方法更简单、更易于理解:只需要创建一个backgroundColorSpan并将其添加到SpannableString中即可,具体步骤如下:
public static SpannableString buildBackgroundColorSpan(SpannableString spannableString,
String text, String searchString, int color) {
int indexOf = text.toUpperCase().indexOf(searchString.toUpperCase());
try {
spannableString.setSpan(new BackgroundColorSpan(color), indexOf,
(indexOf + searchString.length()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
}
return spannableString;
}
"spannableString"是一个SpannableString对象,假设已经用"text"初始化;"searchString"表示您希望在TextView中“高亮”显示的文本片段,而“color”则是“高亮”文本应设置的背景颜色。
String text = "The Quick Brown Fox Jumps over the Lazy Dog";
String searchString = "brown";
int color = Color.parseColor("#FFF5F19E");
SpannableString spannableString = new SpannableString(text);
spannableString = StringUtils.buildBackgroundColorSpan(spannableString, text, searchString, color);
Spannable str = new SpannableStringBuilder("How can I achieve such an effect with an Android TextView. It looks somehow like selected text and I couldn't find something similar in the API.");
str.setSpan(new NewSpannableClass(), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
((TextView)findViewById(R.id.text)).setText(str);
这里是一个示例,NewSpannableClass
是自定义的Spannable。
考虑到很多人懒得查找如何创建自定义Spannable,以下是一个示例。
public class CustomSpannable extends ClickableSpan
{
@Override public void updateDrawState(TextPaint ds)
{
super.updateDrawState(ds);
ds.setUnderlineText(true);
}
}
TextPaint
改变跨度文本的外观。 <TextView
android:id="@+id/TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#ffffff"
android:background="#1bgtbgt"/>
尝试:
text.setBackgroundColor( int color);
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000FF"
android:textColor="#FFFFFF" />
选取颜色,请使用以下链接 http://html-color-codes.info/
红色:#750A0A
蓝色:#002BFF
绿色:#33FF00
白色:#FFFFFF
黑色:#000000
match_parent
,假设它嵌套在一个跨越整个屏幕长度的父级值中,您的文本将具有相同的长度,但框将增加到整个屏幕的长度。在.xml
文件中的textview
下面尝试以下代码:
<TextView android:background="#0000FF">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#FFFFFF"
android:text="@string/text" />
</LinearLayout>
尝试使用此代码设置文本背景颜色
<TextView
android:id="@+id/comment_dis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Stack Overflow
android:textColor="#ffffff"
android:background="#3cabdc"/>