TextView 组件本身可以显示URL,EMAIL等特殊信息,这些特殊信息都会以连接形式显示...

浪子不回头ぞ 提交于 2019-12-25 20:18:45

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

public class AndrodTActivity extends Activity implements OnClickListener {
 TextView tv_;
 TextView tv1;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  // 点击tv1时,让其跳转到我们自定义的位置  使用android.text.style.ClickableSpan类可以自定义单击URL连接的动作。
  tv_ = (TextView) findViewById(R.id.tv_);
  String text = tv_.getText().toString();
  SpannableString span = new SpannableString(text);
  span.setSpan(new ClickableSpan() {
   @Override
   public void onClick(View widget) {
    Toast.makeText(getApplicationContext(), "hello activity", Toast.LENGTH_SHORT).show();
   }
  }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  // 使用SpannabelString对象设置TextView组件内容
  tv_.setText(span);
  tv_.setMovementMethod(LinkMovementMethod.getInstance());


  // TextView中的个别字设置为超链接,或者设置个别字的颜色、字体等
  tv1 = (TextView) findViewById(R.id.tv1);
  SpannableString sp = new SpannableString("这句话中有百度超链接,有高亮显示,这样,或者这样,还有斜体.");
  // 设置超连接
  URLSpan urlSpan = new URLSpan("http://www.baidu.com");
  sp.setSpan(urlSpan, 5, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  // 设置高亮样式一
  sp.setSpan(new BackgroundColorSpan(Color.RED), 17, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  // 设置高亮样式二
  sp.setSpan(new ForegroundColorSpan(Color.YELLOW), 20, 24, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
  // 设置斜体
  sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 27, 29, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
  // 将sp设置给TextView
  tv1.setText(sp);
  tv1.setMovementMethod(LinkMovementMethod.getInstance());
 }

 @Override
 public void onClick(View v) {

 }

}

 

同时设置文本的颜色与背景色 可以写个通用的类

代码:

public class ColorSpan extends CharacterStyle {
 private int mTextColor;
 private int mBackgroundColor;

 public ColorSpan(int mTextColor, int mBackgroundColor) {
  super();
  this.mTextColor = mTextColor;
  this.mBackgroundColor = mBackgroundColor;
 }

 @Override
 public void updateDrawState(TextPaint tp) {
  tp.bgColor = mBackgroundColor;
  tp.setColor(mTextColor);
 }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!