2013-06-18 97 views
0

我在TextView中有一些带有链接的文本。现在我想让浏览器打开链接,如果用户点击它。我的TextView看起来是这样的:显示正确点击TextView中的链接

<string name="Info">Go to <a href="www.google.com">Google</a></string> 

<TextView 
     android:id="@+id/Info" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="@dimen/OptionMarginBottom" 
     android:autoLink="web" 
     android:linksClickable="true" 
     android:text="@string/Info" /> 

中的链接,蓝色,但我不能点击它。这是为什么?

回答

2

使用这种方法

public static void addLink(TextView textView, String patternToMatch, 
     final String link) { 
    Linkify.TransformFilter filter = new Linkify.TransformFilter() { 
     @Override public String transformUrl(Matcher match, String url) { 
      return link; 
     } 
    }; 
    Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null, 
      filter); 
} 

和使用作为

addLink(text, "^Android", "http://abhiandroidinfo.blogspot.in"); 
+0

作品很好谢谢你!但是我必须从TextView中删除'LinksClickable'和'AutoLink'。 – Cilenco

1

使用LinkifyTextView

Linkify.addLinks(yourTextviewObject, Linkify.WEB_URLS); 

Linkify拿一块文本和正则表达式,并关闭所有的 正则表达式在文成可点击的链接匹配。

+0

不起作用。什么都没有发生 – Cilenco

+0

textview包含一个网站?像http://www.google.com之类的东西? 。如果你想要html方法,你可以在你的textview中使用yourTextviewObject.setText(Html.fromHtml(getString(R.string.info)))设置文本。 – Blackbelt

+0

TextView包含上面带有文本和链接的字符串'请转至Google' – Cilenco

0

helper方法:

public static void addLinks(TextView textView, String linkThis, String toThis) { 
     Pattern pattern = Pattern.compile(linkThis); 
     String scheme = toThis; 
     android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() { 
      @Override 
      public boolean acceptMatch(CharSequence s, int start, int end) { 
       return true; 
      } 
     }, new TransformFilter() { 

      @Override 
      public String transformUrl(Matcher match, String url) { 
       return ""; 
      } 
     }); 
    } 

现在使用如下:

String weblink = "WebsiteName"; 
String url = course.getString(TAG_Info); 

TextView txtInfo= (TextView) findViewById(R.id.Info); 
txtInfo.setText(userCanSeeThis); 

addLinks(txtInfo, weblink, url); 
0

简单的方法是做一个字符串,并添加链接文本 和xml文件,使TextView的:

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:autoLink="web" 
    android:text="@string/string_with_link" />