Preferred method for handling OnClick?


  1. That Don Guy

    That Don Guy Member

    I have noticed three different ways of handling a Button click:

    First, put the handling code into the setOnClickListener call:
    Code (Text):

    <Button android:id="@+id/someButton"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/Click" />

    -----

    final Button someButton = (Button) findViewById(R.id.someButton);
    someButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // handle someButton's click
        }
    });
    Second, use OnClickListener with parameter "this", and handle the click in a separate onClick call:
    Code (Text):

    <Button android:id="@+id/someButton"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/Click" />

    -----

    final Button someButton = (Button) findViewById(R.id.someButton);
    someButton.setOnClickListener(this);

    @Override
    public void onClick(View v)
    {
        if (v == someButton)
        {
            // handle someButton's click
        }
    }
    Third, include android.onClick in the XML:
    Code (Text):

    <Button android:id="@+id/someButton"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/Click"
            android:onClick="someButton_Click" />

    -----

    public void someButton_Click(View v)
    {
        // handle someButton's click
    }
    Are there any advantages in using one of these ways over the others?

    -- Don

    Advertisement
    :
  2. JamTheMan

    JamTheMan Well-Known Member

    I, for one, always use a generic onClick handler defined in the xml and then with a switch case for all the buttons in a single activity.
    Not for any specific performance reasons, I just find it easier to maintain, and it creates fewer lines of code...
Loading...

Share This Page