字符串作为TextView中的链接

时间:2013-04-03 01:00:37

标签: android string android-layout hyperlink textview

public String getVisualFormInUI(){
    return "Name         :  "+ name +
    "\nRating        :  " + rating +  
    "\nPhone number : " + phoneNumber + 
    "\nAddress      : " + address + 
    "\nMobile Url   : " + mobileUrl ;
}

这是我的活动中textview的字符串值。是否可以将移动网址仅表示为链接而其他网址不是?而且无需创建其他TextView对象。

4 个答案:

答案 0 :(得分:3)

请参阅此问题:Links in TextView

或者:

textView.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."));
textView.setMovementMethod(LinkMovementMethod.getInstance());

答案 1 :(得分:3)

让Android将您的String呈现为HTML内容,如下所示:

yourTextView.setText(Html.fromHtml(yourString));

然后,如果你在它周围包装一个超链接引用,你可以将mobileUrl显示为链接:

<a href='"+ mobileUrl +"'>"+ mobileUrl +"</a>

答案 2 :(得分:1)

如果您希望将网址作为链接,则只需在XML布局文件中使用<TextView>的{​​{3}}属性即可。如果您想使用更具描述性的消息作为链接,您可以使用锚标记并按@ spatulamania的答案中所述调用setMovementMethod()

答案 3 :(得分:0)

  

如果您使用HTML命令,则无需链接URL和数字   遵循以下表示字符串的方式。

->假设您在strings.xml文件夹中有字符串

    <string name="string_name">Welcome to www.google.com .It is the worlds best online search engine.</string>

->现在在您的xml文件TextView小部件中添加以下属性。

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textSize="15dp"
           android:autoLink="all"
           android:textColor="@color/colorBlack"
           android:text="@string/string_name"
           android:id="@+id/id_string_name_textView" />

魔术发生了。只需运行代码并查看更改,这些更改将自动允许链接URL和数字。

如果您想提供描述性数据来链接字符串,请使用以下语句以编程方式对TextView

string_name_textView.setMovementMethod(LinkMovementMethod.getInstance());