Android TextView部分文字实现点击事件

This is the class for text whose content and markup can both be changed.
(这是一个内容和标记都可以更改的文本类)
快速实现
直接看代码:


@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.tvContent); final SpannableStringBuilder style = new SpannableStringBuilder(); //设置文字 style.append("注册即为同意《某某某协议》"); //设置部分文字点击事件 ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, "触发点击事件!", Toast.LENGTH_SHORT).show(); } }; style.setSpan(clickableSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(style); //设置部分文字颜色 ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF")); style.setSpan(foregroundColorSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //配置给TextView tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(style); }


简单介绍一下SpannableStringBuilder,这个类实际上就是对你的TextView中的文字进行简单的配置,配置好你想要的属性后,直接调用下面代码即可:

//设置光标如何移动计量的方法
textView.setMovementMethod(LinkMovementMethod.getInstance());
//配置给TextView
textView.setText(style)
如何进行各个属性的配置呢?我们以字体设置颜色为例:

//设置部分文字颜色

//创建字体颜色的Span,并初始化字体颜色属性
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
//我们设置第7~13个中间的字符为蓝色
style.setSpan(foregroundColorSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableStringBuilder和SpannableString主要通过使用setSpan(Object what, int start, int end, int flags)改变文本样式。

setSpan()方法对应的参数如下:

start: 指定Span的开始位置
end: 指定Span的结束位置,并不包括这个位置。
flags:取值有如下四个
Spannable. SPAN_INCLUSIVE_EXCLUSIVE:前面包括,后面不包括,即在文本前插入新的文本会应用该样式,而在文本后插入新文本不会应用该样式
Spannable. SPAN_INCLUSIVE_INCLUSIVE:前面包括,后面包括,即在文本前插入新的文本会应用该样式,而在文本后插入新文本也会应用该样式
Spannable. SPAN_EXCLUSIVE_EXCLUSIVE:前面不包括,后面不包括
Spannable. SPAN_EXCLUSIVE_INCLUSIVE:前面不包括,后面包括
详细实现方式都已经在【Android】强大的SpannableStringBuilder @带心情去旅行 中有很清楚的讲解,大家去原作者家查阅即可。



 

猜你喜欢

转载自www.cnblogs.com/Alex80/p/11823976.html