Thanks Mark. That clears up everything.

On Sat, Dec 6, 2008 at 8:55 AM, Mark Murphy <[EMAIL PROTECTED]> wrote:

>
> Josh Dobbs wrote:
> > This is what i have
> > that seems to work but i have to create a new listener for each
> > button(currently i only have one as you see below)
> > I couldnt get your method to work. can you tell me what im doing wrong?
>
> <snip>
>
>  >         btn1.setOnClickListener(new View.OnClickListener() {
>  >             public void onClick(View view) {
>  >
>  >             }
>  >
>  >         });
>
> Here, you are creating an anonymous inner class (the new
> View.OnClickListener() stuff). That's fine, but if you want to use the
> same anonymous inner class instance, you'll need to hang onto it.
>
> One approach for this is to assign it to a member variable in the outer
> class:
>
> View.OnClickListener hitMe=new View.OnClickListener() {
>         public void onClick(View view) {
>                // something
>        }
> };
>
> Then, you can use that same listener object for each of your buttons:
>
> btn1.setOnClickListener(hitMe);
> btn2.setOnClickListener(hitMe);
>
> Another approach is to make the inner class not anonymous, making it a
> named inner class:
>
> public class PegLites extends Activity {
>         // other stuff here
>
>        class ButtonListener implements View.OnClickListener {
>                 public void onClick(View view) {
>                         // something
>                }
>        }
> }
>
> Then, you can create new listener objects per button, but they would
> share the same implementation of onClick():
>
> btn1.setOnClickListener(new ButtonListener());
> btn2.setOnClickListener(new ButtonListener());
>
> For a pure listener implementing an interface, as in this case, either
> approach should work and be safe, since the listener holds no state. If
> there is a chance the listener will hold some state, though, you are
> better served going with the named inner class approach, so each button
> can have its own listener with its own state.
>
> --
> Mark Murphy (a Commons Guy)
> http://commonsware.com
> _The Busy Coder's Guide to Android Development_ Version 1.9 Published!
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to