public class MainActivity extends Activity {
TextView _tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_tv = (TextView) findViewById( R.id.textView1 );
String sentence = "this is [part 1 clickable] and [part 2 clickable] and [part 3 clickable]";
_tv.setMovementMethod(LinkMovementMethod.getInstance());
_tv.setText(addClickablePart(sentence), BufferType.SPANNABLE);
}
private SpannableStringBuilder addClickablePart(String str) {
SpannableStringBuilder ssb = new SpannableStringBuilder(str);
int idx1 = str.indexOf("[");
int idx2 = 0;
while (idx1 != -1) {
idx2 = str.indexOf("]", idx1) + 1;
final String clickString = str.substring(idx1, idx2);
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, clickString,
Toast.LENGTH_SHORT).show();
}
}, idx1, idx2, 0);
idx1 = str.indexOf("[", idx2);
}
return ssb;
}
}
编辑
public class MainActivity extends Activity {
TextView _tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_tv = (TextView) findViewById( R.id.textView1 );
SpannableString ss = new SpannableString("Android is a Software stack");
ss.setSpan(new MyClickableSpan(), 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//22 to 27 stack is clickable
ss.setSpan(new MyClickableSpan(), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//0 to 7 Android is clickable
_tv.setText(ss);
_tv.setMovementMethod(LinkMovementMethod.getInstance());
}
class MyClickableSpan extends ClickableSpan{ //clickable span
public void onClick(View textView) {
//do something
Toast.makeText(MainActivity.this, "Clicked",
Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.GREEN);//set text color
ds.setUnderlineText(false); // set to false to remove underline
}
}
}
有关 ClickableSpan 的更多信息http://developer.android.com/reference/android/text/style/ClickableSpan.html
您还可以通过设置粗体、斜体或设置字体大小来设置可扩展字符串的样式。
StyleSpan boldSpan = new StyleSpan( Typeface.ITALIC );
ss.setSpan( boldSpan, 22, 27, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
StyleSpan boldSpan1 = new StyleSpan(Typeface.BOLD);
ss.setSpan(new RelativeSizeSpan(3f), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//set fontsize
ss.setSpan( boldSpan1, 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );