【转】android:为TextView添加样式——下划线,颜色,设置链接样式及前背景色
最近弄了弄好久没有弄得android,帮着改一个客户端,遇到了上面的这个问题,记下,自己用了,还是对的:
实现下划线及颜色设置:
public class AtActivity extends Activity {
LinearLayout ll;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll=(LinearLayout)findViewById(R.id.ll);
TextView tv=new TextView(this);
tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
tv.setText("使用代码实现下划线样式");
tv.setTextColor(Color.WHITE);
ll.addView(tv);
tv=new TextView(this);
tv.setText(Html.fromHtml("<u>使用html实现下划线样式</u>"));
ll.addView(tv);
}
}
设置超链接样式:默认的超链接是蓝色的,我们现在设置成前景红色
public class AtActivity extends Activity {
LinearLayout ll;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll=(LinearLayout)findViewById(R.id.ll);
TextView tv=new TextView(this);
tv.setText(Html.fromHtml("<a href=\"http://blog.csdn.net/CAIYUNFREEDOM\">自定义的超链接样式</a>"));
tv.setMovementMethod(LinkMovementMethod.getInstance());
CharSequence text = tv.getText();
if (text instanceof Spannable){
int end = text.length();
Spannable sp = (Spannable)tv.getText();
URLSpan[] urls = sp.getSpans( 0 , end, URLSpan.class );
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.clearSpans(); // should clear old spans
for (URLSpan url : urls){
URLSpan myURLSpan= new URLSpan(url.getURL());
style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.RED), sp.getSpanStart(url), sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//设置前景色为红色
}
tv.setText(style);
}
ll.addView(tv);
tv=new TextView(this);
tv.setText(Html.fromHtml("<a href=\"http://blog.csdn.net/CAIYUNFREEDOM\">默认的超链接样式</a>"));
tv.setMovementMethod(LinkMovementMethod.getInstance());
ll.addView(tv);
}
}
原文地址:http://blog.csdn.net/caiyunfreedom/article/details/6763834