I have an activity with two fragments: one for showing products in a grid view, and the other to show the products that the user adds to the order (ListFragment). When the user clicks a product in the grid view, what I need is to display a dialog (DialogFragment) in which I ask the quantity of product wanted. Then, when the user clicks Accept in the dialog, I want the product to appear in the ListFragment.
On one hand, I have to pass the product object to the dialog in order to show its name as the dialog's title (for example). So what I did was to pass it this way:
public static class ProductDialog extends DialogFragment {
static ProductDialog newInstance(ProductVO product) {
ProductDialog f = new ProductDialog();
Bundle args = new Bundle();
args.putSerializable("product", product);
f.setArguments(args);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ProductVO product = (ProductVO) getArguments().getSerializable("product");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_dialog_add)
.setTitle(R.string.add_product)
...
.setPositiveButton(R.string.accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}
)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}
)
.create();
}
}
I think that that's okay, please correct me if I'm wrong. But then, in the onClick event of the positive button, I have to retrieve the quantity introduced in the dialog and pass it to the other fragment (the ListFragment), moment in which it should be displayed in the list instantly.
How could I do that?
Thanks in advance
The recommended approach is to communicate from the DialogFragment to the Activity using an Interface, and then from the Activity to the Fragment.
In your activity:
Then the DialogFragment inner class
The XML for R.layout.alert_dialog_text_entry is from the API Demos. It doesn't fit your use case of getting a quantity from the user, but it illustrates using a custom layout to get a value from the user.