How do I handle callbacks for multiple buttons?

android, android-activity, android-fragments

Solution

You can let your Fragment implement interface. Then it'll look like this:

 //init buttons somewhere
 button.setOnClickListener(this);
 anotherButton.setOnClickListener(this);

 //that's a Fragment method
 public void onClick(View v)
   {
      switch(v.getId()){
          case R.id.button1:
            doStuff();
          break;
          case R.id.button2:
            doStuff();
          break;
      }
   }

Problem

I'm pretty new to Android development and I am trying to handle multiple button clicks from a fragment class to my activity. I was able to figure out how to handle one click by creating a listener in my fragment class and then having the activity class implement that interface. myFragment.java ``` onResetGridListener mCallback; // Container activity must implement this interface public interface onResetGridListener { public void ResetGridClicked(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.tilemap, container, false); Button button = (Button) view.findViewById(R.id.resetGrid_button); // A simple OnClickListener for our button. You can see here how a Fragment can encapsulate // logic and views to build out re-usable Activity components. button.setOnClickListener(new OnClickListener() { public void onClick(View v) { mCallback.ResetGridClicked(); } }); return view; } ``` This works perfectly, however I have another button in the same fragment now and many more to come so I was wondering how to handle this. Can the activity implement more than one interface (one for each button) or am I going about this the wrong way? Thank you for your time and information

Original source