android - 为一个小部件设置 AppWidget 背景也会影响其他小部件

标签 android android-appwidget

我的小部件的布局文件从顶层开始:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/widget_margin"
    android:id="@+id/widget"
    android:background="#20000000" >

因此,起始背景是半透明的。然后在执行过程中的某个时刻,我调用以下命令使背景完全透明:

remoteViews.setInt(R.id.widget, "setBackgroundColor", Color.parseColor("#00000000"));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

虽然这有效,但我发现当添加另一个小部件时,该小部件的背景开始时是完全透明的,而不是按照布局 xml 的半透明。就好像为一个小部件设置背景颜色已经改变了所有小部件,包括随后添加的新小部件。

现在这很奇怪,因为与上面的代码 fragment 同时,我还向小部件添加了一个位图(通过 RemoteViews):

remoteViews.setImageViewBitmap(R.id.imageView, bmp);

...并且那个位图没有出现在所有后续的小部件中,所以我使用的基本方法似乎是合理的。

那么为什么背景会传播到其他小部件?

编辑以根据评论中的要求添加 appWidgetId 的派生:

基本上来自 Intent,例如在小部件的配置 ActivityonCreate() 中:

Intent intent = getIntent();
Bundle extras = intent.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

最佳答案

在您的 AppWidgetProvider 类中,您覆盖了 onUpdate 方法。最后一个参数是 appWidgetIds,它是当前 Activity 小部件 ID 的数组。很可能你实现了改变背景颜色,循环遍历每个 widgetId 的数组。为了能够为每个小部件定义自定义背景,您需要实现将所需背景映射到特定 widgetId 的逻辑,并在循环内遵循该逻辑。

关于android - 为一个小部件设置 AppWidget 背景也会影响其他小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469712/

相关文章:

Android 小部件未更新 - 小部件 ID 不正确

android - Android 界面生成器(用户界面设计器)

php - 无法在 Android 中使用 PHP 脚本插入 MySQL

android - 错误 : 1 on building Gradle android studio 3. 3.1

android - 如何为 Android 应用小部件指定标签/名称

android - AppWidget 第一次添加时没有完成更新

Android:向 ListView App Widget 添加多个 View

android - PathTooLongException Xamarin Droid 项目

java - 如何在Gradle中排除可传递jar依赖关系?

android - 当 AppWidget 不再可见时是否有 AppWidget 回调?