DialogFragment
from within an Activity
and want to request an action or pass data from the DialogFragment
to the Activity
. The best, cleanest way I find to do so is by means of local broadcasts. Here's how...First, define a
BroadcastReceiver
in your Activity
as follows:
private class LocalBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// safety check
if (intent == null || intent.getAction() == null) {
return;
}
if (intent.getAction().equals("SOME_ACTION")) {
doSomeAction();
}
}
}
Second, declare an instance of LocalBroadcastReceiver
in your Activity
, as follows:
private BroadcastReceiver localBroadcastReceiver;
Third, instantiate the BroadcastReceiver
in the activity's onCreate(Bundle)
method:
localBroadcastReceiver = new LocalBroadcastReceiver();
Fourth, register for the activity to listen out for the local broadcasts in the activity's onResume()
method:
LocalBroadcastManager.getInstance(this).registerReceiver(
localBroadcastReceiver,
new IntentFilter("SOME_ACTION"));
Fifth, unregister the broadcast receiver in the activity's onPause()
method:
LocalBroadcastManager.getInstance(this).unregisterReceiver(
localBroadcastReceiver);
Sixth and final, send the broadcast from wherever makes sense in your DialogFragment
, as follows:
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(
new Intent("SOME_ACTION"));
7 comments:
Do you have to register anything in the manifest?
No, no need to register anything in the manifest for local broadcasts.
I am using 2 spinners on the dialog , when i press 'ok' the value of these spinners should be passed back to the main activity.
the challenge is how do i read the values of spinners ? i dont see any findViewById in AlertDialog
Vivek, your question (how to obtain the value in a Spinner in an AlertDialog) is off topic from this post. Please post your question on a programmer forum like Stack Overflow.
its only taking back us to calling activity ...but how to send data from dialog fragment to the activity?
Omkar, which activity do you want to send data to if not the calling activity??
Thank you brother. It is help me.
Post a Comment