0

Is it possible to make an onClickListener app-global?

I basically have several fragments that will use the same numpad buttons for input and instead of registering and filtering click events for each button in each fragment I wanted to ask if it was possible to share an onClickListener throughout the entire app.

This is the setting:

public class LoginFragment extends Fragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle states) {
    this.context = getActivity();

    // TODO: Register onClickListener...somehow

    context.registerReceiver(receiver, filter); //For the intent listening
    view = inflater.inflate(R.layout.layout_login_screen, container, false);
    buildUI(null);
    return view;
  }

(and two different fragments simmilar to this one)

and then the idea was:

public class NumPadListener implements OnClickListener {

  @Override
  public void onClick(View v) {
    System.out.println("Yup...I'm listening?");

    // TODO: Do funny intent stuff here
  }

}

Is this even possible? And if yes, how? :) If it isn't, do you have any recommendations on how to implement this in the best way? Thanks

AreusAstarte
  • 1,958
  • 2
  • 17
  • 29
  • button.setOnClickListener(new NumPadListener()); – dymmeh Feb 14 '13 at 22:19
  • Ah...I feel retarded now. I tried to set the onClickListener in the same step as getting the button view, causing it to tell me that void couldn't be cast to Button (obv...) thanks^^ – AreusAstarte Feb 14 '13 at 22:29

1 Answers1

0

Yes, as dymmeh has shown. But the proper way is probably to create your own view component containing all the numpad buttons. You would need to define a layout file, and create a class which would extend some kind of ViewGroup (see compound controls).

This custom component would take care of onClick events of buttons inside it. You could then expose some kind of interface (listener) for activities and fragments to attach to if you need them to react for higher-level events.

Then, you would just include your custom component in any layouts you need instead of copypasting a bunch of buttons and the onClick listener-attaching code.

kar
  • 741
  • 6
  • 16