1

I have the following Layout:

<LinearLayout
    android:id="@+id/group_button_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:layout_centerHorizontal="true">

    <Button
        android:id="@+id/group_button_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:text="Week"/>

    <Button
        android:id="@+id/group_button_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:padding="0dp"
        android:text="Month"/>

    <Button
        android:id="@+id/group_button_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:text="Quarter"/>

    <Button
        android:id="@+id/group_button_4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:text="Half Year"/>
</LinearLayout>

I created the onClickListener on layout like that:

 private void initViews() {
     mGroupedButtonLayout = (LinearLayout) findViewById(R.id.group_button_layout);
 }

 private void initListeners() {
     mGroupedButtonLayout.setOnClickListener(mButtonGroupListener);
 }

And I thought that after click on a button onClick event will be triggered:

private View.OnClickListener mButtonGroupListener = new View.OnClickListener() {
    public void onClick(View v) {
        Logger.d("Clicked");
        Logger.d(String.valueOf(v.getId()));
        // do something when the button is clicked
    }
};

Is it possible to catch onClick event on every button without the need to create a listener for each button?

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
redrom
  • 11,502
  • 31
  • 157
  • 264

1 Answers1

2

You could set the android:onClick attribute for the buttons, and handle your logic in the method you point it to.

XML

<Button
    android:id="@+id/group_button_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="12sp"
    android:text="Week"
    android:onClick="doButtonClick"/>

Java

public void doButtonClick(View v) {
    switch(v.getId()) {
    case R.id.group_button_1:
        //do whatever for this button
        break;
    default:
        break;
}
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55