【问题标题】:Why link does not work in the text view?为什么链接在文本视图中不起作用?
【发布时间】:2013-09-05 10:38:02
【问题描述】:

我的 TextView 中有链接:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    ...

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="all"
        android:linksClickable="true"
        android:text="@string/app_description" />
</RelativeLayout>

链接是资源的一部分:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <string name="app_description">Some text with the <a href="http://www.example.com">link</a>.</string>
</resources>

不知何故链接不起作用。可能是什么原因? 它显示为链接。但是单击不会打开浏览器。

类代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

【问题讨论】:

标签: android hyperlink textview


【解决方案1】:

你可以这样使用http链接:

   mLink = (TextView) findViewById(R.id.link);
      if (mLink != null) {
        mLink.setMovementMethod(LinkMovementMethod.getInstance());
     }

在 XML 中:

android:autoLink="all"

【讨论】:

【解决方案2】:

重要,如果您正在使用:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<a href=https://www.google.com/>Click</a>", Html.FROM_HTML_MODE_LEGACY));
} else {
    textView.setText(Html.fromHtml("<a href=https://www.google.com/>Click</a>"));
}
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());

不要在 xml 中设置android:autoLink="all"android:autoLink="web",因为这样不起作用!

【讨论】:

    【解决方案3】:

    TextView yourTextView = (TextView) findViewById(R.id.yourTextViewId );

        yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
        Spannable spans = (Spannable) yourTextView.getText();
    
        ClickableSpan clickSpan = new ClickableSpan() {
    
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
    
                case R.id.yourTextViewId :
                    Intent localIntent = new Intent();
                    localIntent.setAction("android.intent.action.VIEW");
                    localIntent.setData(Uri.parse("YOUR LINK"));
                    startActivity(localIntent);
                    break;
                }
    
            }
        };
        spans.setSpan(clickSpan, 0, spans.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    【讨论】:

      【解决方案4】:

      以下代码对我有用。

      String html2 = "<br><br>Fire - <b><a href=http://www.google.com>google</a> </b></br></br>";
              text.append(Html.fromHtml(html2));
              text.setMovementMethod(LinkMovementMethod.getInstance());
      

      【讨论】:

        猜你喜欢
        • 2015-11-06
        • 2011-07-08
        • 1970-01-01
        • 2011-10-26
        • 1970-01-01
        • 2011-12-12
        • 2022-01-12
        • 1970-01-01
        • 2021-04-10
        相关资源
        最近更新 更多