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 ???
Buttons should have different ids:
Now, to set the listener for all, a solution would be to get the
id
of all buttons in an array, and then use a "for" loop to set the listener for each.Like this:
Just create a named function instead of an anonymous one:
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.
if your buttons are in the LinearLayout, in the RelativeLayour or in the other. And you have very many buttons.
xml file for example...