I have code which styles standard Android widgets programmatically (not from XML). The code is working, but I have this bunch of if instanceof else if instanceof
block which is ugly.
I have read discussions on Stack Overflow, and my conclusion is instanceof
is better on my case, but I'm not so sure, maybe I'm missing something?
public static void styleAllControls2(Context c, List<View> controls, CxpResources cxpr) {
if (cxpr == null) {
return;
}
File xfiles = c.getExternalFilesDir(null);
if (xfiles == null) {
Log.e(TAG, "couldnt get external files dir!");
return;
}
Resources res = c.getResources();
String filepath = xfiles.getAbsolutePath() + File.separator;
for (View view : controls) {
ViewModifier vModfr = null;
if (view instanceof RatingBar) {
// viewModifier = new RatingBarModifier(res, cxpr, filepath);
} else if (view instanceof SeekBar) {
vModfr = new SeekBarModifier(res, cxpr, filepath);
} else if (view instanceof ProgressBar) {
vModfr = new ProgressBarModifier(res, cxpr, filepath);
} else if (view instanceof CheckBox) {
vModfr = new CheckBoxModifier(res, cxpr, filepath);
} else if (view instanceof RadioButton) {
vModfr = new RadioButtonModifier(res, cxpr, filepath);
} else if (view instanceof Switch) {
vModfr = new SwitchModifier(res, cxpr, filepath);
} else if (view instanceof ToggleButton) {
vModfr = new ToggleButtonModifier(res, cxpr, filepath);
} else if (view instanceof Button) {
vModfr = new ButtonModifier(res, cxpr, filepath);
} else if (view instanceof Spinner) {
vModfr = new SpinnerModifier(res, cxpr, filepath);
} else if (view instanceof EditText) {
vModfr = new EditTextModifier(res, cxpr, filepath);
}
if (vModfr != null) {
vModfr.modify(view);
}
}
}
ViewModifier
class:
public abstract class ViewModifier<T extends View> {
private static final String TAG = "ViewModifier";
protected final CxpResources cxpResources;
protected final String basedir;
protected final Resources resources;
protected final TypedValue typedValue;
public ViewModifier(Resources resources, CxpResources cxpResources, final String basedir) {
this.resources = resources;
this.cxpResources = cxpResources;
this.basedir = basedir;
typedValue = new TypedValue();
typedValue.density = resources.getDisplayMetrics().densityDpi;
}
public abstract void modify(T v);
// some helper codes....
}
All xxxModifier
class inherit from ViewModifier
class.
My questions:
- Is a bunch of
instanceof
s really the best way? As far as I know, I can't use visitor pattern because I can't modify Android widgets. - Am I using generics right? Particularly in
ViewModifier
class signature. - Which is better, my current implementation, or to make
modify
an interface and then havexxxModifier
classes implement that?ViewModifier
has a bunch of helper methods though. - Review of my code in general, according to Android and Java best practices and conventions.
- Intellij Idea / Android Studio tricks to help self-review perhaps?