onLongClick listener for group of buttons in Android

Massih picture Massih · Jul 3, 2013 · Viewed 13.4k times · Source

In my Android application, I want to create a fragment that works like a keypad. I have one function which handle onClick for all 9 keys. I want to know is there anyway to write just one function to handle onLongClick for all these 9 keys too.

here is layout xml :

   <Button
    android:id="@id/testButton"
    android:layout_width="70dp"
    android:layout_height="55dp"
    android:layout_margin="2dp"
    android:background="@drawable/keypad_round_button"
    android:text="1"
    android:textColor="@color/black_1" 
    android:onClick="keypadSetNote"
    android:longClickable="true"/>
<Button
    android:id="@id/testButton"
    android:layout_width="70dp"
    android:layout_height="55dp"
    android:layout_margin="2dp"
    android:background="@drawable/keypad_round_button"
    android:text="2"
    android:longClickable="true"
    android:textColor="@color/black_1"
    android:onClick="keypadSetNote"
     />

Here is OnlongClick listener :

        Button button = (Button) findViewById(R.id.testButton);
    button.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View v) {
            Button clickedButton = (Button) v;
            String buttonText = clickedButton.getText().toString();
            Log.v(TAG, "button long pressed --> " + buttonText);
            return true;
        }
    });

I gave all keys same ID to handle all onLongClick actions in one function, but it just work for the first key. Is there anyway to define something like group button in Android ??? Or I have to write OnLongClick listener for all of them separately ???

Answer

Jorge Fuentes Gonz&#225;lez picture Jorge Fuentes González · Jul 3, 2013

Just create a named function instead of an anonymous one:

View.OnLongClickListener listener = new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        Button clickedButton = (Button) v;
        String buttonText = clickedButton.getText().toString();
        Log.v(TAG, "button long pressed --> " + buttonText);
        return true;
    }
};

button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
button3.setOnLongClickListener(listener);

And, altough you don't asked it, we must warn you: As @AndyRes says, your buttons must have differents ids. Having the same ID doesn't mean that getting the button by id will return all buttons, only will return the first button with that ID, that's because it only works with the first button.