Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I assign a "default" OnClickListener() for an Android Activity?
    text
    copied!<p>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 each widget in the view?</p> <p>================================================</p> <p><strong>UPDATE</strong></p> <p>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 <strong>Misc.setDefaultClickHandler(this, this)</strong>. Naturally your Activity needs to implement the View.OnclickListener interface.</p> <pre><code>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 &lt; 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); } } </code></pre> <p>-- roschler</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload