TextView上的Html.fromHtml()无法动态添加布局

时间:2015-09-23 01:38:25

标签: android android-layout

我使用Html.fromHtml()函数在多个屏幕中设置TextView的文本。所有这些都具有以下模式:<a href="http://link.com">Name</a>。我使用Log来查看字符串是否正确,它们是。

但是这两个案例中有一个常见的事情是不起作用:我正在膨胀和复制行布局。

我使用LinearLayout作为行,并在另一个linearlayout中添加多个这些行。

正在复制的行布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="3">

    <TextView
        android:id="@+id/bandName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:layout_marginTop="15dp"
        android:text="Band"
        android:textColor="@color/darkTxtLightBg"
        android:textColorLink="@color/darkTxtLightBg"
        android:clickable="true"
        android:linksClickable="true"
        android:textSize="17sp" />

    <TextView
        android:id="@+id/bandOnTour"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="15dp"
        android:gravity="end"
        android:text="Band"
        android:textColor="@color/darkTxtLightBg"
        android:textSize="16sp" />
</LinearLayout>

我插入行的LinearLayout:

<LinearLayout
        android:id="@+id/table_bandList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="vertical"
        android:layout_marginTop="10dp">

</LinearLayout>

我复制,填充和添加这些视图的代码:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout tr;
for (Band b : bandsFollowed) {
     tr = (LinearLayout) inflater.inflate(R.layout.bandrow_followedlist, null);
     TextView t1 = (TextView) tr.findViewById(R.id.bandName);
     t1.setText(Html.fromHtml("<a href=\"" + b.url + "\">" + b.name + "</a>"));
     t1 = (TextView) tr.findViewById(R.id.bandOnTour);
     t1.setText(getResources().getString(R.string.onTour));
     t1.setTextColor(getResources().getColor(R.color.bandFollowed));
     tl.addView(tr);
}

我尝试了什么:

  • 将所有父级布局设置为android:clickable="true",但没有任何区别。
  • android:onClick属性与函数一起使用,但是我不需要这样做。
  • 使用TableLayout和TableRows而不是LinearLayouts,但我遇到了同样的问题。

那么,为什么我只是将文本设置为我拥有的另一个TextView,但是当我动态添加它时它不起作用?可能是inflater,父级甚至是xml文件吗?

我知道链接是存在的,因为文本带有下划线,但是当我点击它时没有任何反应。

1 个答案:

答案 0 :(得分:1)

尝试以下代码,我已经测试过了。希望这有帮助!

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        final String htmlString="<a href=\"http://www.google.com\">Go to Google</a>";
        textView.setText(Html.fromHtml(htmlString));
相关问题