clickable word inside TextView in android

This should do the trick. Just change your edittext’s text in the OnClickListener. It may be able to be reduced but this should work.

private void foo() {
    SpannableString link = makeLinkSpan("click here", new View.OnClickListener() {          
        @Override
        public void onClick(View v) {
            // respond to click
        }
    });

    // We need a TextView instance.        
    TextView tv = new TextView(context);   

    // Set the TextView's text     
    tv.setText("To perform action, ");

    // Append the link we created above using a function defined below.
    tv.append(link);

    // Append a period (this will not be a link).
    tv.append(".");

    // This line makes the link clickable!
    makeLinksFocusable(tv);
}

/*
 * Methods used above.
 */

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;
}

private void makeLinksFocusable(TextView tv) {
    MovementMethod m = tv.getMovementMethod();  
    if ((m == null) || !(m instanceof LinkMovementMethod)) {  
        if (tv.getLinksClickable()) {  
            tv.setMovementMethod(LinkMovementMethod.getInstance());  
        }  
    }  
}

/*
 * 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);  
    }        
}

Leave a Comment