Tru*_*gDQ 18 android onclick textview clickable
我正在ClickableSpan使用TextView,我正在尝试获取单击的跨度文本.这是我的代码.
// 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);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我设置clickablespan了的TextView字符12到17,我想在拿到这些字符onClick事件.
无论如何我能做到吗?或者至少我可以将12, 17参数传递给onClick事件吗?
谢谢!
psk*_*ink 35
试试这个:
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) + "]");
}
}
Run Code Online (Sandbox Code Playgroud)
稍微简单一点,如果需要也可以传递模型参考.
public class SpecialClickableSpan extends ClickableSpan {
String text;
public SpecialClickableSpan(String text){
super();
this.text = text;
}
@Override
public void onClick(View widget) {
Log.d(TAG, "onClick [" + text + "]");
}
}
Run Code Online (Sandbox Code Playgroud)
然后调用新的SpecialClickableSpan("我的文本")
| 归档时间: |
|
| 查看次数: |
13375 次 |
| 最近记录: |