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 );