【问题标题】:Setting AppWidget background for one widget affects others too为一个小部件设置 AppWidget 背景也会影响其他小部件
【发布时间】:2016-02-17 23:17:28
【问题描述】:

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

<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 的半透明。就好像为一个小部件设置背景颜色已经改变了所有小部件,包括随后添加的新小部件。

现在这很奇怪,因为在上面的 sn-p 的同时,我还添加了一个位图到小部件中(通过RemoteViews):

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

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

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

编辑以添加appWidgetId 的推导作为评论中的要求:

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

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

【问题讨论】:

  • 你能告诉我们你如何创建这个小部件以及如何添加新元素吗?
  • 你在哪里添加remoteViews.setImageViewBitmap(R.id.imageView, bmp);

标签: android android-appwidget


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-03-09
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多