4

I have a Textview with location:

eg. "Mountain View, CA"

What I want to achieve is to create this text to act like a Link - color,underline, focusability etc.

This link doesn't need to direct anywhere - surrounding view has attached onClick listener that fires google maps intent.

DonGru
  • 13,532
  • 8
  • 45
  • 55
pixel
  • 24,905
  • 36
  • 149
  • 251

4 Answers4

16

Something like this should work.

  TextView location = (TextView) findViewById(R.id.location);
  location.setMovementMethod(LinkMovementMethod.getInstance());
  Spannable spans = (Spannable) location.getText();
  ClickableSpan clickSpan = new ClickableSpan() {

     @Override
     public void onClick(View widget)
     {
        //put whatever you like here, below is an example
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        builder.setTitle("Location clicked");
        AlertDialog dialog = builder.create();            
        dialog.show();
     }
  };
  spans.setSpan(clickSpan, 0, spans.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ageektrapped
  • 14,482
  • 7
  • 57
  • 72
3

there is a example in ApiDemos which can solve your problem. Check out com.example.android.apis.text.Link class, it may help. Following is part of the code:

TextView t3 = (TextView) findViewById(R.id.text3);
t3.setText(
        Html.fromHtml(
            "<b>text3:</b>  Text with a " +
            "<a href=\"http://www.google.com\">link</a> " +
            "created in the Java source code using HTML."));
t3.setMovementMethod(LinkMovementMethod.getInstance());
DonGru
  • 13,532
  • 8
  • 45
  • 55
Tony
  • 1,581
  • 11
  • 24
0

tv.setMovementMethod(LinkMovementMethod.getInstance());

if you are not getting click callback

diesel
  • 3,296
  • 1
  • 20
  • 17
0

you can use Spannable class with mTextView.scollTo() to create internal link