简体   繁体   中英

How to update widget using widget id?

I'm implementing yet another battery widget :) I want to let user choose widget apparence on start, so actually my initial layout looks like that:

    <ImageView
    android:id="@+id/battery_image_purple"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:contentDescription="battery image"
    android:src="@drawable/purple_p10"
    android:visibility="invisible" />

<ImageView
    android:id="@+id/battery_image_orange"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:contentDescription="battery image"
    android:src="@drawable/orange_p10"
    android:visibility="invisible" />

When widget is added to home screen user saves desired variant to shared prefferences as key - widget id value - variant id.

Next I want set visibility depending on that combination:

                AppWidgetManager widgetManager = AppWidgetManager
                    .getInstance(getApplicationContext());
            RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
            for (int i = 0; i < widgetIds.length; i++) {

                widgetManager.updateAppWidget(widgetIds[i], rv);


                SharedPreferences preferences = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                int widgetVariant = preferences.getInt(
                        "ID"+widgetIds[i], 0);
                int batteryImageId=0;
                switch(widgetVariant){
                case 0:
                    batteryImageId = R.id.battery_image_purple;
                    break;
                case 1:
                    batteryImageId = R.id.battery_image_orange;
                    break;
                case 2:
                    batteryImageId = R.id.battery_image_blue;
                    break;
                }
                rv.setViewVisibility(batteryImageId, View.VISIBLE);



            }

My problem is, that code above updates ALL instances of widget with last saved settings - how to apply changes only to specific widget Id?

I believe this line determines whether it updates all apps of that kind, or just the one you choose:

for (int i = 0; i < widgetIds.length; i++) {
}

Try removing it?

Also I think that this line must go at the end of what you're doing:

widgetManager.updateAppWidget(widgetIds[i], rv);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM