多次包含时在布局中设置 Android RemoteViews 的文本

Set text of Android RemoteViews inside layout when include it multiple times

我指的是这个问题: How do I access the views inside the layout when I reuse it multiple times?

我有以下两种布局:

<!-- layout_to_include.xml -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

<!-- widget.xml -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/included_layout_1"
        layout="@layout/layout_to_include"/>

    <include
        android:id="@+id/included_layout_2"
        layout="@layout/layout_to_include"/>

</LinearLayout>

通常,您可以像这样在包含的布局中以编程方式访问 TextView:

LinearLayout l1 = (LinearLayout) findViewById(R.id.included_layout_1);
((TextView) l1.findViewById(R.id.text_view)).setText("test1");

LinearLayout l2 = (LinearLayout) findViewById(R.id.included_layout_2);
((TextView) l2.findViewById(R.id.text_view)).setText("test2");

但就我而言,我有一个 Android AppWidget,它只能通过 RemoteViews 访问:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.text_view, "test1");

这只会更改第一个 TextView 的文本。

我还没有找到任何解决方案,所以我的问题是是否可以在多个包含的布局中设置 TextView 的文本。

可以做到。

删除您的 include;您需要以编程方式添加 (别无他法 AFAIK),因此将 id(例如 LinearLayout)添加到您的小部件的线性布局,并且:

RemoteViews one = new RemoteViews(getPackageName(), R.layout.layout_to_include);
one.setTextViewText(R.id.text_view, "tv-ONE"); // <---
remoteViews.addView(R.id.LinearLayout, one);

RemoteViews two = new RemoteViews(getPackageName(), R.layout.layout_to_include);
two.setTextViewText(R.id.text_view, "tv-TWO"); // <---
remoteViews.addView(R.id.LinearLayout, two);