lrony* 2010-04-29 01:41 采纳率: 0%
浏览 653
已采纳

我如何使链接在一个 TextView 点击?

I have the following TextView defined:

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:autoLink="web" android:id="@+id/infoTxtCredits"
    android:layout_centerInParent="true"
    android:linksClickable="true"></TextView>

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a>.

Android is highlighting the links in the TextView, but they do not respond to clicks. Can someone tell me what I'm doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?

Looks like it has to do with the way I define my string resource. This does not work:

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

But this does:

<string name="txtCredits">www.google.com</string>

Which is a bummer because I would much rather show a text link than show the full URL.

转载于:https://stackoverflow.com/questions/2734270/how-do-i-make-links-in-a-textview-clickable

  • 写回答

30条回答 默认 最新

  • 喵-见缝插针 2010-04-30 18:18
    关注

    Buried in the API demos I found the solution to my problem:

    Link.java:

        // text2 has links specified by putting <a> tags in the string
        // resource.  By default these links will appear but not
        // respond to user input.  To make them active, you need to
        // call setMovementMethod() on the TextView object.
    
        TextView t2 = (TextView) findViewById(R.id.text2);
        t2.setMovementMethod(LinkMovementMethod.getInstance());
    

    I removed most of the attributes on my TextView to match what was in the demo.

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtCredits"/>
    

    That solved it. Pretty difficult to uncover and fix.

    Important: Don't forget to remove autoLink="web" if you are calling setMovementMethod().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样