I am implementing a modal dialog in my Android application, allowing the user to either pick a player from a list, or create one with predefined traits.
PlayerPickerListener
public interface PlayerPickerListener {
Activity getActivity();
void playerCreated();
}
PlayerPicker (extends Dialog)
public PlayerPicker(Context context, String title, final PlayerPickerListener listener) {
super(context);
setTitle(title);
setContentView(R.layout.player_dialog);
View.OnClickListener changeHandler = new View.OnClickListener() {
@Override
public void onClick(View v) {
// PlayersActivity is basically a ListView selecting the player
Intent intent = new Intent(listener.getActivity(), PlayersActivity.class);
intent.putExtra(REQ_CODE, SELECT_ACTION);
listener.getActivity().startActivityForResult(intent, SELECT_ACTION);
}
};
Button b = (Button) findViewById(R.id.button_change);
b.setOnClickListener(changeHandler);
View.OnClickListener newHandler = new View.OnClickListener() {
@Override
public void onClick(View v) {
EntityPlayer player = PlayerManager.createNewPlayer();
listener.playerCreated();
}
};
b = (Button) findViewById(R.id.button_new);
b.setOnClickListener(newHandler);
}
MainActivity (implements PlayerPickerListener)
public Activity getActivity() { return this; }
public void displayPlayer(View view) {
myPlayerPicker = new PlayerPicker(this, "Pick a player", this);
myPlayerPicker.show();
}
public void playerCreated() {
myPlayerPicker.dismiss();
// some extra stuff
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PlayersActivity.SELECT_ACTION && resultCode == RESULT_OK && data != null) {
myPlayerPicker.dismiss();
// some extra stuff
}
super.onActivityResult(requestCode, resultCode, data);
}
I have the following issues with my approach:
- I am led to add the
getActivity()
method in my listener, because I have no other way of starting an intent from the Dialog. I need an intent to go to my ListView and return with a result. - Because of the above behavior, I am calling
dismiss()
on my Dialog from inside my Activity. For the new player case, I could easily add the dismissal of the Dialog inside theOnClickListener
, but I am leaving it on the Activity just to have a type of uniform behavior.
My main question is whether it is common practice to dismiss a Dialog in its own code, or externally.
I'd argue that it would not seem natural for a dialog to be shut down from another source. A Dialog should disappear when its objective is complete. Is this bad design?