Tickled Pink Tickled Pink - 1 year ago 93
Android Question

How to read button touches in table?

What's the correct way to test for button touches in a table of buttons (custom keypad)? OnTouch Listeners for every button seems cumbersome.

Answer Source

It's not cumbersome. However I would suggest using the same listener for all of them. (And this is using OnTouchListener; OnClickListener may be better in your case.)

public class MyButtonTouchListener implements OnTouchListener {
    public boolean onTouch(View v, MotionEvent ev) {
        Button b = (Button) v;
        String buttonText = b.getText().toString();
        // Do whatever, based on buttonText. Example: if (buttonText.equals("#")) { doPound(); }

Then, you create one of these items, and assign it to all of them.

MyButtonTouchListener listener = new MyButtonTouchListener();
ArrayList<Button> myButtons = new ArrayList<Button>();
// Add all your Button objects to the ArrayList.
for (Button b : myButtons)

Now, your listener only appears once in memory, and each item still has unique functionality.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download