Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes you are right, there is a better way. A single TouchListener that handles everything, determining which button it is via the id.</p> <pre><code>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; } } </code></pre> <p>And that's how you'd do it! A numerical approach for the id's is very helpful in this case. Another approach is to have your activity implement the OnTouchListener in your activity, and then your code would be even simpler.</p> <pre><code>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; } } </code></pre> <p>Note: This approach also will also work for OnClickListener, OnCheckedChangeListener, or any other listener that you would set on an Android view.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload