Android: Returning values from a custom Dialog
February 19, 2010 at 10:37 am 3 comments
Context:
Cases which involve using a custom dialog to capture user input, may require the captured data to be passed back to the displaying activity. The following describes exactly this… how to pass back data from a custom dialog to the displaying activity.
ps – by custom dialog we mean a custom class that ‘extends Dialog‘.
Solution:
Step 1 – Define custom interface
// step 1 - to return values from dialog
public interface OnFooEventListener {
public void fooEvent(int fieldOne, int fieldTwo);
}
Step 2 – Declare the above interface as a field member
// step 2 - to return values from dialog private OnFooEventListener onFooEventListener;
Step 3 – Add it to the custom dialog constructor
// step 3 - to return values from dialog
public FooEventDialog(Context context, OnFooEventListener onFooEventListener)
{
super(context);
this.context = context;
this.onFooEventListener = onFooEventListener;
}
Step 4 – Call it within the view object’s event listener, (in this case an ‘ok’ button)
Button btnOk = (Button) findViewById(R.id.btnSet);
btnOk.setOnClickListener( new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// step 4 - to return values from dialog
onFooEventListener.fooEvent(fieldOne, fieldTwo);
dismiss();
}
});
Overview – So the class should look something like the following
public class FooEventDialog extends Dialog
{
// step 1
public interface OnFooEventListener {
public void fooEvent(int fieldOne, int fieldTwo);
}
// step 2
private OnFooEventListener onFooEventListener;
// Other member fields
...
// step 3
public FooEventDialog(Context context, OnFooEventListener onFooEventListener)
{ ... }
@Override
public void onCreate(Bundle savedInstanceState)
{
// other stuff
...
Button btnOk = (Button) findViewById(R.id.btnSet);
btnOk.setOnClickListener( new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// step 4 - to return values from dialog
onFooEventListener.fooEvent(fieldOne, fieldTwo);
dismiss();
}
});
}
}
… That’s all there is to it.
Wa’Allahu A’lam !
Entry filed under: Android, Eclipse. Tags: Android Custom Dialog, Customer Dialog Interface, Dialog event listener, Dialog UI Listener, extends Dialog implement, Returng values from custom dialog, Returning values from a custom dialog.
1.
Lisa | June 5, 2010 at 5:09 am
But what if you want the calling activity to receive the dialog onclick response?
FooEventDialog dialog = new FooEventDialog(this);
dialog.show();
above doesn’t work… it wants to pass in the event listener… do i attach a listener to the parent?
2.
wtaylor | July 25, 2010 at 6:08 am
Can you please post code for the call back on the main activity.
3.
Marcelo Mariano | July 25, 2011 at 12:01 pm
Oh my god..
Here is the solution..
http://javamariano.blogspot.com/2011/07/how-to-get-values-in-android.html