Yes, you are right, there is a better way. One TouchListener that processes everything, determining which button is found through the identifier.
void intialization(){ Button m1, m2, m3, m4; ... //do initialization stuff m1.setId(1); m2.setId(2); m3.setId(3); m4.setId(4); MyTouchListener touchListener = new MyTouchListener(); m1.setOnTouchListener(touchListener); m2.setOnTouchListener(touchListener); m3.setOnTouchListener(touchListener); m4.setOnTouchListener(touchListener); } public class MyTouchListener implements OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { switch(v.getId()){ case 1: //do stuff for button 1 break; case 2: //do stuff for button 2 break; case 3: //do stuff for button 3 break; case 4: //do stuff for button 4 break; } return true; } }
And how do you do it! In this case, a numerical approach to the identifier is very useful. Another approach is for your activity to run OnTouchListener in your activity, and then your code would be even simpler.
public class MyActivity extends Activity implements OnTouchListener { void initialization(){ Button m1, m2, m3, m4; ... //do initialization stuff m1.setId(1); m2.setId(2); m3.setId(3); m4.setId(4); m1.setOnTouchListener(this); m2.setOnTouchListener(this); m3.setOnTouchListener(this); m4.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { switch(v.getId()){ case 1: //do stuff for button 1 break; case 2: //do stuff for button 2 break; case 3: //do stuff for button 3 break; case 4: //do stuff for button 4 break; } return true; } }
Note. This approach will also work for OnClickListener, OnCheckedChangeListener or any other listener that you would install on the Android screen.
source share