1

I was creating a chat application where each time I type some text and press send, I create a new TextView programmatically and add to my existing LinearLayout like this -

public void addTextView(LinearLayout view, String text) {
        TextView chatTextView = new TextView(getActivity());
        chatTextView.setLinksClickable(true);
        chatTextView.setMovementMethod(LinkMovementMethod.getInstance());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        chatTextView.setLayoutParams(lp);
       // chatTextView.setAutoLinkMask(Linkify.ALL);
        chatTextView.setText("me: " + Html.fromHtml(text));
        view.addView(chatTextView);    
    }

As per answer 1 and this question I added
chatTextView.setMovementMethod(LinkMovementMethod.getInstance()); to this TextView but still my link is not clickable. (Testing on an emulator, this code is in a fragment)

Text I am trying to add here is -

<a href="http://www.google.com">url</a>

Have tried -

  1. autoLink = web (it will highlight direct urls (ie www.google.com) but not hyperlinks (ie href).
  2. Linkify.WEB_URL

EDIT

I tested right now and found that setMovementMethod works fine with hyperlinks if textview is from xml layout, but if it is dynamic, it doesn't work.

Community
  • 1
  • 1
Darpan
  • 5,623
  • 3
  • 48
  • 80

3 Answers3

1

you can use this:

String text = "<font color=#ff0000><b><u>"+ "click here" +"</b></u></font>";
textview.setText(Html.fromHtml(text));
textview.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Intent internetIntent = new Intent(Intent.ACTION_VIEW,
                                        Uri.parse("http://www.google.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
                                        internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        context.startActivity(internetIntent);
                                    }
                                });
Akshay Paliwal
  • 3,718
  • 2
  • 39
  • 43
1

Use this

TextView textView =(TextView)findViewById(R.id.textView);
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
textView.setText(Html.fromHtml(text));
Logic
  • 2,230
  • 2
  • 24
  • 41
0
    mTextView.setClickable(true);
    final String text  = Html.fromHtml(getActivity().getResources().getString(R.string.url)).toString();
    mTextView.setMovementMethod(LinkMovementMethod.getInstance());
    mTextView.setText(text);

string.xml

<string name="url"><a href='http://www.google.com'> Google </a></string>

this is working perfect for me, try it

Abhishek
  • 1,337
  • 10
  • 29