android:为TextView添加样式——下划线,颜色,设置链接样式及前背景色

  • Post author:
  • Post category:其他


实现下划线及颜色设置:


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);

}

}







版权声明:本文为CAIYUNFREEDOM原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。