1

我指的是这样一个问题: 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> 

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

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的文本。

回答

0

可以做到。

删除您的include s;您需要添加编程(没有其他办法AFAIK),所以加ID(例如LinearLayout)到Widget的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);