Handling Button clicks events android

Response to click

To  create interactive UI you have to use the click events in your application. You can add click events to any view  you want.  In this guide how can we handle the click events in android.
Technical Coding

In Android studio there are two methods available to handle the click events. I will discuss both of them in this guide so you can decide which is the best method for you.

Before we start you have to remember something

  • The view you want to click on must have an unique ID.
  • The ID have to be the unique each view.
Now let's start with our first method
  1. Add this attribute to a view that you want to click on android:onclick.
  2. Give a value to this attribute.Like "submit".
  3. Now go to MainActivity.java file where write java code.
Technical Coding
 4. Here we type code 


public void submit(View view) {
    // after the click
}

Now I explain the second method

Like previous method give the view an ID.
Then move onto the Java code editor the method that we use is a onclicklistener.
           But first we have to identify the view with unique ID. Real declared the button programmatically rather than XML layout so it will initiate the button at runtime.


Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Do something in response to button click
    }
});

Post a Comment

0 Comments