Markonionini Markonionini - 3 months ago 19
Android Question

Showing clickable link inside of the textView

Does someone know how to show a clickable link inside of the

textView
(or any appropriate view).That
textView
is located inside Recycler row.
I am getting a string response from JSON feed and inside that string, there is a link to some webpage.
When the user clicks that link, I want it to open the browser and go to that page.
Also I am trying to handle that click inside of
onBindViewHolder
method in Recycler View adapter .
I tried setting
android:autoLink="web"
in xml and
setMovementMethod(LinkMovementMethod.getInstance())
in java for this
textView
, but it doesn't work and gives me this error:
" FATAL EXCEPTION: main android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? "


If there is a better way for handling these situations, please let me know.

Answer

Use SpannableString.

For eg: I am going to apply clickable for register text(which has blue color with underlined) means,

String text ="Don't have an account? Register";
     SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ForegroundColorSpan(getResources()
                .getColor(R.color.blue)), 23, 31, 0);// i am applying for Register alone. so starting count is 23 and end count is 31.
        ClickableSpan clickableSpan = new SpaceAdjust(text) {
            @Override
            public void onClick(View textView) {
               //here perform your stuff
            }
        };
        spannableString.setSpan(clickableSpan, 23, 31,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

if you need to make text clicable with underline. use this method.

    import android.text.TextPaint;
    import android.text.style.ClickableSpan;
    import android.view.View;

      /**
       * SpaceAdjust.java
      * 
      * This is the class that is used to display underline text
       */
    public class SpaceAdjust extends ClickableSpan {

     /** The clicked. */
      String clicked;

     /**
      * Instantiates a new space adjust.
      * 
      * @param string
      *            the string
      */
      public SpaceAdjust(String string) {
        super();
        clicked = string;
       }

      /*
       * (non-Javadoc)
       * 
      * @see android.text.style.ClickableSpan#onClick(android.view.View)
      */
      public void onClick(View tv) {
        // Un used Code .. Implemented Method
      }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.text.style.ClickableSpan#updateDrawState(android.text.TextPaint)
     */
    public void updateDrawState(TextPaint ds) {
        ds.setUnderlineText(true); // if you don't want to use underline text, just make this as false.
    }
}