AKA I’m as mad as hell at Java and not taking it any more Part II.
When developing Android applications, binding resources to end method calls is even more annoying than binding resources to variables.
One approach is to create an anonymous inner classes implementing various listener interface.
UIButton postButton = (Button) findViewById(R.id.share_post);
postButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do stuff ...
}
}
The other is to just implement the listener interface with whatever activity you’re using and figure out what button is being pressed.
I’d just as soon have the data wired up automatically to functions if it’s there. Here’s how I’m doing it now.
In MyActivity:
// class fields
public ImageButton uiButtonDining;
// in onCreate
UIHelper.bindImageButtons(this);
This will automatically wire to the following function
public void uiButtonDining_onClick(ImageButton _imageButton)
{
// ... do stuff ...
}
I’ve only done this for ImageButton so far but I’m hoping this approach will scale for various other widgets.
The Code
Here’s The Magic for UIHelper.java:
static public void bindImageButtons(final Activity _activity) {
Field[] instance_fields = _activity.getClass().getDeclaredFields();
for (final Field instance_field : instance_fields) {
if (!ImageButton.class.isAssignableFrom(instance_field.getType())) {
continue;
}
LogHelper.debug(true, _activity, "field=" + instance_field.getName());
try {
final ImageButton button = (ImageButton) instance_field.get(_activity);
if (button == null) {
LogHelper.debug(true, _activity,
"Button is stil NULL", "field=" + instance_field.getName());
continue;
}
String callback_onClick_name = instance_field.getName() + "_onClick";
try {
final Method callback_onClick = _activity.getClass().getMethod(
callback_onClick_name, ImageButton.class);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LogHelper.debug(false, _activity, "clicked", "field=" + instance_field.getName());
try {
callback_onClick.invoke(_activity, button);
} catch (IllegalAccessException x) {
LogHelper.debug(true, _activity,
"Couldn't invoke callback", "callback=", callback_onClick, x);
} catch (InvocationTargetException x) {
LogHelper.debug(true, _activity,
"Couldn't invoke callback", "callback=", callback_onClick, x);
}
}
});
} catch (NoSuchMethodException x) {
LogHelper.debug(true, _activity,
"no callback", "method=", callback_onClick_name);
}
} catch (IllegalAccessException x) {
LogHelper.debug(true, _activity,
"Can't set R.id", "name=", instance_field.getName(), x);
}
}
}