I have a widget (AppWidgetProvider) and i want to know if there is a way to support multiple clicks.Example:
1)If is the first click on the widget, then the ImageButton of the widget changes (for example, changes the color).
2)If is the second time, then open an Activity.
-- There is some way to handle click events inside AppWidgetProvider?
My code:
public class MyWidgetProvider extends AppWidgetProvider
{
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_widget);
views.setOnClickPendingIntent(R.id.asdf, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
My widget is working fine. When i click the ImageButton(R.id.asdf), it goes to the activity MyActivity.
Id like to know how can i handle click events on my widget to make a different action (example: change the color of the ImageButton) instead of go to some activity. Is there some other way to some click handle besides setOnClickPendingIntent()?
Maybe this could help. It works for me:
}
Why not just count the clicks yourself?
I did it this way:
1)If is the first click on the widget, then the ImageButton of the widget changes
2)If is the second time, then open an Activity and return to the inicial ImageButton state.
Im handling click events with setOnClickPendingIntent:
Don't count it in a listener (it's ridiculous, you don't know when your widget will be recycled from the memory and you will lose the value of int clicks)
Persist the number of clicks (add +1 each time it is clicked, restart to 0 when you reach the end of the click "cycle", the end of different click behaviors).
You could persist them in a database, with serialization, or with the shared preferences (I guess the preferences are the easiest way)
Unlike
Button
and its subclasses,AppWidget
doesn't have the concept of anonClickListener
.AppWidget
s have to provide aPendingIntent
for the application that hosts them to fire when the widget is clicked. If you wanted to track multiple clicks, you would need to have a receiver that filters on an intent specific to your widget and keeps track of how many times it has received it.Slightly-less-relevant: You might reconsider your behavior model. Android is a one-click-to-take-action environment that doesn't have the same "click-once-to-select" concept like you'd find in, say, Windows. By emulating that behavior, your widget won't behave like all of the other UI elements and may cause confusion. Additionally, if there are two of your widgets on the screen and the user taps one and then the other, both will appear "selected," which probably isn't what you want.
This is what I'm doing. Works beautifully =]