最近项目需要用到textview为特定字符设置不同的颜色,如果用不同的控件拼起来的话一行也许没有问题,但是如果换行的话效果就不理想了就像qq空间回复品论的效果,昵称和内容文字颜色不一样,点击事件也不一样。 目前我找到两张方法,效果一样。想用哪种看个人喜好
。
1,使用html格式
String html = "看这里,测试<u>下划线</u>、<i>斜体字</i>、<font color=‘red‘>红色字</font>的格式";
tv.setText(Html.fromHtml(html));
怎样让TextView也显示Html中节点的图像呢?
可以看到fromHtml还有另一个重构:
fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
实现一下ImageGetter就可以让图片显示了
ImageGetter imgGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = null;
drawable = Drawable.createFromPath(source); // Or fetch it from the URL
// Important
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
return drawable;
}
};
tv.setText(Html.fromHtml(html, imgGetter, null));
2.使用SpannableString
tv.setText(getSpan());
tv.setHighlightColor(Color.TRANSPARENT);//去掉点击效果
tv.setMovementMethod(LinkMovementMethod.getInstance());//这句话必须有,
private SpannableString getSpan(){
final View.OnClickListener l=new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(MainActivity.this,WebViewActivity.class);
intent.putExtra("url", "http://www.caiyanlicai.com/app/H5/privacy.html");
startActivity(intent);
overridePendingTransition(R.drawable.push_left_in,R.drawable.push_left_out);
}
};
final View.OnClickListener l2=new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(MainActivity.this,WebViewActivity.class);
intent.putExtra("url", "http://www.caiyanlicai.com/app/H5/agreement.html");
startActivity(intent);
overridePendingTransition(R.drawable.push_left_in,R.drawable.push_left_out);
}
};
String one="瞬间爆炸";
String two="完成单杀";
String and=" 和 ";
SpannableString spnableInfo=new SpannableString(one+and+two);
int start=one.length()+and.length();
int end=one.length()+two.length()+and.length();
int start2=0;
int end2=one.length();
spnableInfo.setSpan(new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
super.updateDrawState(ds);
ds.setUnderlineText(false);//去掉下划线
}
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
l.onClick(widget);
}
}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spnableInfo.setSpan(new ForegroundColorSpan(Color.parseColor("#007aff")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spnableInfo.setSpan(new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
l2.onClick(widget);
}
}, start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spnableInfo.setSpan(new ForegroundColorSpan(Color.parseColor("#007aff")), start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spnableInfo;
}
时间: 2024-10-09 04:40:59