android - 多次包含时在布局内设置Android RemoteViews的文本

标签 android android-layout android-widget android-remoteview

我指的是这个问题:
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");

但就我而言,我有一个只能通过 RemoteViews 访问的 Android AppWidget:
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);

关于android - 多次包含时在布局内设置Android RemoteViews的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44387434/

相关文章:

Android Progressbar 不旋转并在 Oreo 中出现箭头

android - 为 Android 的默认浏览器或 Chrome 构建插件

安卓三重混合应用

android - 我可以更新后台 Activity 的用户界面吗?

android - 隐藏 SpannableString 网址

android - 当我使用 eclipse 创建新的 android 项目时,它创建了两个 xml 布局

java - NullPointerException - FrameLayout

java - 向可扩展 ListView 添加按钮

java - 一个seekBar的移动会影响其他seekBar

android - 从 ReceiverRestrictedContext 获取应用程序,就好像使用了 getApplication(不是 getApplicationContext)