Is it possible to add onclick to some portion of a textview? For instance my code goes like this,
String content = "Hello this a test.. For more details contact @Peter";
someTextView.setText(content);
I would like to add an onClick event for "@Peter". Is that possible?
TIA.
onClick is prompted deprecated.
To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
We will use this TextView to set on-click listener. Get reference to the the TextView in layout file using id, and then call setOnClickListener {} on this TextView. When user clicks on this TextView, the code inside setOnClickListener {} will be executed.
Simple: -)
SpannableString link = makeLinkSpan("@Peter", new View.OnClickListener() {
@Override
public void onClick(View v) {
// Peforme Click
}
});
String content = "Hello this a test.. For more details contact";
someTextView.setText(content);
someTextView.append(link);
And makeLinkSpan()
method is
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
}
ClickableString
Class
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
@Override
public void onClick(View v) {
mListener.onClick(v);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With