Thanks to some tutorials I have now built my first working little Android Widget.
It has an ImageView which changes it’s image when I click on it once.
But now I want to click on it multiple times to change to another image just like a toggle button.
Therefore I’ve set the following IF constraint in my onReceive method:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
try {
if(counter %2 == 0) {
views.setImageViewResource(R.id.iv1, R.drawable.button_state1);
cn1 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn1, views);
counter++;
} else { counter++;
views.setImageViewResource(R.id.iv1, R.drawable.button_state2);
cn2 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager..getInstance(context).updateAppWidget(cn2, views);
}
}
// ...
}
But it seems to me that I can’t modify my int counter with counter++ persistently.
Is there any way to set the int of my class through a click on my widget or an other solution to build some kind of toggle behavior in a widget?
Is this even possible without a running background service?
In the Else, you fail to increment the counter. Imagine counter is first 0, so then (counter %2 == 0) is true, so it does the first part, and increments the counter. Next time counter is 1, so (counter %2 == 0) is false, so it does the second part… every time from then on, because counter is forever 1! Just increment counter every time.