これは、文字列内の特定の単語にonClickアクションを追加した方法です。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TextView
android:id="@+id/mytextview1"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
</LinearLayout>
主な活動:
public class HtmlTextLinkTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.mytextview1);
tv.setText("Whale and Lion");
clickify(tv, "Whale", new ClickSpan.OnClickListener() {
@Override
public void onClick() {
Toast.makeText(HtmlTextLinkTestActivity.this, "Whale was clicked!", Toast.LENGTH_SHORT).show();
}
});
clickify(tv, "Lion", new ClickSpan.OnClickListener() {
@Override
public void onClick() {
Toast.makeText(HtmlTextLinkTestActivity.this, "Lion was clicked!", Toast.LENGTH_SHORT).show();
}
});
}
public static void clickify(TextView view, final String clickableText, final ClickSpan.OnClickListener listener) {
CharSequence text = view.getText();
String string = text.toString();
ClickSpan span = new ClickSpan(listener);
int start = string.indexOf(clickableText);
int end = start + clickableText.length();
if (start == -1) return;
if (text instanceof Spannable) {
((Spannable)text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
SpannableString s = SpannableString.valueOf(text);
s.setSpan(span, start, end, Spanned.SPAN_MARK_MARK);
view.setText(s);
}
MovementMethod m = view.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
view.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
class ClickSpan extends ClickableSpan {
private OnClickListener mListener;
public ClickSpan(OnClickListener listener) {
mListener = listener;
}
@Override
public void onClick(View widget) {
if (mListener != null) mListener.onClick();
}
public interface OnClickListener {
void onClick();
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(0xff0000ff); // remove this if you don't want to want to override the textView's color if you specified it in main.xml
}
}
あなたはあなたの答えを投稿することができ、私は私の答えを追加しましたあなた – pengwang
に感謝。 – C0deAttack