为一个TextView中的某个单词设置单击事件
为TextView中的字符串“dai ha ha dai lingdaidaing“中的dai单词设置单击事件
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView) findViewById(R.id.tv); String str = "dai ha ha dai lingdaidaing"; SpannableStringBuilder ssb = new SpannableStringBuilder(str); Pattern pattern = Pattern.compile("dai"); Matcher matcher = pattern.matcher(str); while(matcher.find()) { String group = matcher.group(); ClickableSpan cs = new MyClickableSpan(group); ssb.setSpan(cs, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.setText(ssb); textView.setMovementMethod(LinkMovementMethod.getInstance()); } class MyClickableSpan extends ClickableSpan{ private String group; public MyClickableSpan(){} public MyClickableSpan(String group){ this.group = group; } @Override public void onClick(View widget) { Toast.makeText(getApplicationContext(), group, 0).show(); } } }