Can I assign a "default" OnClickListener() for an Android Activity?
I have an Activity that, for each widget in the layout, I call setOnClickListener() to assign my OnClick() handler. In my OnClick() handler I use a switch statement to execute the desired code for each button based on the View parameter's ID. Is there a way to assign a default handler to the main view instead of having to make individual listener assignment calls for e开发者_StackOverflow中文版ach widget in the view?
================================================
UPDATE
Thanks to kcoppock's starting sample I have coded up a complete implementation of a class that has a static method that sets the click handler for all View elements in an Activity to a common click handler. This is for those situations where you have a simple layout and you want to do all the event handling in a common click listener event that uses a switch statement based on the View parameter object's ID. To use it from an Activity, just call Misc.setDefaultClickHandler(this, this). Naturally your Activity needs to implement the View.OnclickListener interface.
package {put your package name here};
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
public class Misc {
public Misc() {
super();
}
// Returns the root view for a given activity.
public static View getRootView(Activity activity) {
return activity.findViewById(android.R.id.content).getRootView();
}
private static void assignClickHandler(View root, View.OnClickListener theOnClickListener) {
// Is it a View or a View group?
if (root instanceof ViewGroup) {
// It's a ViewGroup, process all it's children.
ViewGroup vg = (ViewGroup) root;
for(int i = 0; i < vg.getChildCount(); i++)
// Make recursive call.
assignClickHandler(vg.getChildAt(i), theOnClickListener);
}
else
{
// Child is a View. Set the desired context for the click handler.
root.setOnClickListener(theOnClickListener);
}
}
public static void setDefaultClickHandler(Activity activity, View.OnClickListener theOnClickListener) {
assignClickHandler(getRootView(activity), theOnClickListener);
}
}
-- roschler
Not to my knowledge, but you could just use a loop, something like this:
ViewGroup root = findViewById(R.id.my_root_layout);
final Context context = this;
assignClickHandler(root);
public void assignClickHandler(int root) {
for(int i = 0; i < root.getChildCount(); i++) {
if(root.getChildAt(i) instanceof ViewGroup) {
assignClickHandler(root.getChildAt(i));
}
else {
(root.getChildAt(i)).setOnClickListener(context);
}
}
}
Note it calls recursively for any nested layouts within as well. I haven't tested this so I might have messed up some syntax, but that idea should work, if you're just looking to avoid manually setting every one.
精彩评论