I have a TextView with SpannableString because I want the do differnet thing when user click different position of the view. Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
String str = "ClickMe";
SpannableString spStr = new SpannableString(str);
ClickableSpan clickSpan = new CustomizedClickableSpan(str);
spStr.setSpan(clickSpan, 0, str.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.setText("PlainTextA");
tv.append(spStr);
tv.append("PlainTextB");
tv.setMovementMethod(LinkMovementMethod.getInstance());
setContentView(tv);
}
private class CustomizedClickableSpan extends ClickableSpan {
String text;
public CustomizedClickableSpan(String text) {
super();
this.text = text;
}
@Override
public void onClick(View widget) {
Toast.makeText(SpanTextView.this, text, Toast.LENGTH_SHORT).show();
}
}
After that, the textView's text is "PlainTextAClickMePlainTextB". And when I click the "ClickMe", the toast is showing. (It's just very well.)
But, when I long press the "ClickMe", the app crashed! Here is my log:
java.lang.NullPointerException
at android.widget.Editor.touchPositionIsInSelection(Editor.java:750)
at android.widget.Editor.performLongClick(Editor.java:851)
at android.widget.TextView.performLongClick(TextView.java:8390)
at android.view.View$CheckForLongPress.run(View.java:18419)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5050)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:806)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
at dalvik.system.NativeStart.main(Native Method)
Anyone can help me? Thanks a lot!
EDIT:
Thanks for @Blackbelt . I just add these code:
tv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//just consume the event
return true;
}
});
And the problem is solved!
BTW, what's the reason of the NullPointerException
?