protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1找到控件
tv = (TextView) findViewById(R.id.spantest);
//2 组合好可以点击的字符串
String all = new String(getResources().getString(R.string.testall));
String test1 = new String(getResources().getString(R.string.test1));
String test2 = new String(getResources().getString(R.string.test2));
String format = String.format(all,test1,test2);
int index1 = format.indexOf(test1);
int index2 = format.indexOf(test2);
System.out.println("index1"+index1);
System.out.println("index2"+index2);
SpannableString ss = new SpannableString(format);
ss.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
System.out.println("test 1
click");
}
},index1,index1+test1.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字的前景色
ss.setSpan(new ForegroundColorSpan(Color.RED),index1,index1+test1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置下划线文字
ss.setSpan(new UnderlineSpan(), index1,index1+test1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
System.out.println("test 2
click");
}
},index2,index2+test2.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//3 将字符串设置为文本
tv.setText(ss);
//4让文本的超链接起作用
tv.setMovementMethod(LinkMovementMethod.getInstance());
}