1

Is it possible to add an onClickListener in a static method?

I'm trying to create a convenience class make some common modifications to Crouton (Ben Weiss' implementation based on Cyril Mottier's article). I did have a forked version (where I'd modified the source) but I'm trying to cut down on the library projects I'm dependent on, choosing instead to include the jar he provides in Maven, but the class is set as final so I can't extend it from there.

What I've done is:

public class CroutonEx {

    static Crouton crouton;

    ...

    public static Crouton makeDismissOnClick(Crouton crouton) {
        CroutonEx.crouton = crouton;
        return crouton.setOnClickListener(new View.OnClickListener() {            
            @Override
            public void onClick(View v) {
                Crouton.hide(CroutonEx.crouton);                
            }
        });
    }
}

My questions are:

  • when onClick(View v) is fired, will it be hiding the Crouton stored currently in the CroutonEx.crouton or the one that it was referencing at the point the listener was registered? That is, in my case, it's always going to be the same one (the Crouton is displayed immediately after setting the listener, and only for a few seconds, and only one at a time) but is it guaranteed in the general case (with regards to which object in memory it'll be referring to)?

  • even if this works, it's clearly not an ideal way; while I doubt it'll cause an issue in this particular case (I can't think of how multiple threads would be accessing this method at once (croutons would only be added on the main/UI thread)), is there better way to add listeners in a utility class, or is it discouraged altogether?

Thanks!

(Though this is for an Android project, I didn't add the tag as I didn't think it was relevant.)

zero0
  • 847
  • 11
  • 26
ataulm
  • 15,195
  • 7
  • 50
  • 92
  • When I searched, I didn't find the duplicate question, but it does answer my question on recommended practices. I chose to vote to close rather than delete in case this question leads others to the answer. – ataulm Jun 14 '13 at 10:33
  • Kudos for self-voting to close a question. If you encounter further issues, feel free to let me know. Either here or on GitHub. – Ben Weiss Jun 20 '13 at 12:19

0 Answers0