Handling Click events in Button | Android

There are 2 ways to handle the click event in button

  • Onclick in xml layout
  • Using an OnClickListener

Onclick in XML layout

When the user clicks a button, the Button object receives an on-click event.

To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

NOTE:
If you use this event handler in your code, make sure that you are having that button in your MainActivity. It won’t work if you use this event handler in fragment because onClick attribute only works in Activity or MainActivity.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<Button xmlns:android="http:// schemas.android.com/apk/res/android"
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" 
/>

chevron_right


In MainActivity class

filter_none

edit
close

play_arrow

link
brightness_4
code

/** Called when the user touches the button */
public void sendMessage(View view)
{
    // Do something in response to button click
}

chevron_right


Make sure that your sendMessage method should have the following :

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)
  • Using an OnClickListener

    You can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments.

    There are two ways to do this event handler programmatically :

    • Implementing View.OnClickListener in your Activity or fragment.
    • Creating new anonymous View.OnClickListener.

    Implementing View.OnClickListener in your Activity or fragment

    To implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class.

    Firstly, link the button in xml layout to java by calling findViewById() method.
    R.id.button_send refers the button in XML.

    mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <RelativeLayout
        xmlns:android="http:// schemas.android.com/apk/res/android"
        xmlns:app="http:// schemas.android.com/apk/res-auto"
        xmlns:tools="http:// schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.sample.MainActivity" >
      
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button_send" />
    </RelativeLayout>

    chevron_right

    
    

    MainActivity code:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public class MainActivity extends AppCompatActivity
        implements View.OnClickListener {
        private Button mButton;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            mButton = findViewById(R.id.button_send);
            mButton.setOnClickListener(this);
        }
      
        @Override
        public void onClick(View view)
        {
            switch (view.getId()) {
            case R.id.button_send:
                // Do something
            }
        }
    }

    chevron_right

    
    

    If you have more than one button click event, you can use switch case to identify which button is clicked.

    Creating Anonymous View.OnClickListener

    Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method.

    MainActivity code:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public class MainActivity extends AppCompatActivity {
      
        private Button mButton;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            mButton = findViewById(R.id.button_send);
            mButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    // Do something
                }
            });
        }
    }

    chevron_right

    
    

    setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter.

    It’s like the same in java when you can create a new thread with an anonymous subclass.



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



    Improved By : Vijayaraghavan



    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.