給TextView的部分字符串加超鏈接
阿新 • • 發佈:2017-05-21
mov text main void 控件 ann 字符 mat 劃線 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());
}
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 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
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());
}
給TextView的部分字符串加超鏈接