I wanted to centralise the creation of DialogFragments used to report errors to the user in order to just have a class to which I pass the error code and have the dialog spawned automagically.
In order to handle multiple errors I am using an enum in which I define the error propreties.
public enum DialogError {
TTS_NOT_INSTALLED {
@Override
public int getTitleResource() {
return R.string.error_tts_not_installed_title;
}
@Override
public int getMessageResource() {
return R.string.error_tts_not_installed_message;
}
@Override
public int getPositiveButtonResource() {
return R.string.error_tts_not_installed_button_positive;
}
@Override
public void onPositiveButtonClick() {
// TODO
}
@Override
public int getNegativeButtonResource() {
return R.string.error_tts_not_installed_button_negative;
}
@Override
public void onNegativeButtonClick() {
// TODO
}
};
public abstract int getTitleResource();
public abstract int getMessageResource();
public abstract int getPositiveButtonResource();
public abstract void onPositiveButtonClick();
public abstract int getNegativeButtonResource();
public abstract void onNegativeButtonClick();
}
Then I have my FragmentDialogError class that I call to create a new Dialog.
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
public class FragmentDialogError
extends DialogFragment {
Context context;
DialogError error;
public FragmentDialogError(Context context, DialogError error) {
this.context = context;
this.error = error;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setTitle(error.getTitleResource())
.setMessage(error.getMessageResource())
.setPositiveButton(error.getPositiveButtonResource(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
error.onPositiveButtonClick();
}
})
.setNegativeButton(error.getNegativeButtonResource(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
error.onNegativeButtonClick();
}
});
return builder.create();
}
}
My problem now is that I can't obviously call functions such as startActivity inside of my enum's onPositiveButtonClick() or onNegativeButtonClick().
One soluction would be using a switch() in FragmentDialogError but this way I would split the code between the enum and the class. Another one would be to define in some way the actions that a button press could trigger and let handle them to another class, but I'm looking for a clean and elegant soluction.
How can I implement this in Java keeping the code tidy?
0 comments:
Post a Comment