Reputation: 485
I am trying to create a button in my app's widget. I expect it to open a dialog box when clicked. I am unsure of how to implement this. Here is the widget's code:
public class IncompleteTodosWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
Intent intent = new Intent(context, timeTypeSelector.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
/* context = */ context,
/* requestCode = */ 0,
/* intent = */ intent,
/* flags = */ PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.incomplete_todos_widget);
views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
}
Here is the code of the dialog box:
public class timeTypeSelector extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Demo message")
.setPositiveButton("Perform miracles", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("Bitcoin has reached 69,42,000");
}
})
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("Bitcoin would have reached 69,42,000 if you had clicked the other button");
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
When I try clicking the view with id appwidget_text, my app gets opened instead of the dialog box. Where am I going wrong?
Upvotes: 1
Views: 765
Reputation: 579
Hej Pro,
a PendingIntent cannot target a DialogFragment
directly - only Activity, Service or Broadcast.
You have to set an action on your Intent to identify the click on the view with id (R.id.appwidget_text). When your app is opened and check the received Intent if it is the action for displaying your DialogFragment
and navigate to it.
Upvotes: 1