我正在 ClickableSpan
在一个TextView,而我试图让点击范围的文本。这是我的code。
I'm working on ClickableSpan
in a TextView, and I'm trying to get the clicked span's text. This is my code.
// this is the text we'll be operating on
SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");
// make "dolor" (characters 12 to 17) display a toast message when touched
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
// This will get "Lorem ipsum dolor sit amet", but I just want "dolor"
String text = ((TextView) view).getText().toString();
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
};
text.setSpan(clickableSpan, 12, 17, 0);
正如你所看到的,我设置了 clickablespan
中的的TextView
字符12至17日,我想得到这些字符的的onClick
事件。
As you can see, I set the clickablespan
the the TextView
to characters 12 to 17, and I want to get these characters in the onClick
event.
反正我能做到这一点?或者至少,我可以通过 12,17
参数的onClick
事件?
Is there anyway I can do that? Or at least can I pass the 12, 17
parameter to onClick
event?
感谢您!
试试这个:
public class LoremIpsumSpan extends ClickableSpan {
@Override
public void onClick(View widget) {
// TODO add check if widget instanceof TextView
TextView tv = (TextView) widget;
// TODO add check if tv.getText() instanceof Spanned
Spanned s = (Spanned) tv.getText();
int start = s.getSpanStart(this);
int end = s.getSpanEnd(this);
Log.d(TAG, "onClick [" + s.subSequence(start, end) + "]");
}
}