public class NewItemDialogFragment extends android.support.v4.app.DialogFragment {
...
public static NewItemDialogFragment newInstance() {
return new NewItemDialogFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hasPrice = false;
hasQuantity = false;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.new_item_dialog_fragment, container, false);
ButterKnife.bind(this, mView);
return mView;
}
/**
* Interface that allows parent activity retrieve information from
* dialog.
*/
public interface OnCompleteListener {
void onComplete (final Bundle bundle);
}
/**
* Save the item.
*/
@OnClick(R.id.btn_save)
protected void save() {
Bundle bundle = new Bundle();
String name = mItemName.getText().toString();
int quantity = 0;
int price = 0;
if (!name.equals("")) {
bundle.putString(ITEM_NAME, name);
if (hasQuantity) {
quantity = Integer.parseInt(mQuantity.getText().toString());
bundle.putInt(QUANTITY, quantity);
}
if (hasPrice) {
price = Integer.parseInt(mPrice.getText().toString());
bundle.putInt(PRICE, price);
}
mOnCompleteListener.onComplete(bundle);
}
cancel();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mOnCompleteListener = (OnCompleteListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement NewItemDialogFragment");
}
}
}