--ADVERTISEMENT--

In this example, I will show you two methods to handle button onClick event in android. Handling android button onClick listener is not much difficult but many new developers get problem with onClick method and search for solution. So, here I’m going to show two best methods to handle onClick in android button and almost all developers use these methods to handle onClick.

Related:
Android Menu - Handling Option Menu Item Click
Buttons - Android Button Examples

Create a new Android Project


Application Name: Android Button onClick
Company Domain: viralandroid.com
Package Name: com.viralandroid.androidbuttononclick
Minimum SDK: Android 2.2 (API 8 Froyo)

Add two buttons to your XML activity layout file


I’m going to show you two types of on click in android button. So, first you have to add two buttons in your xml layout file and your code looks like this.
res/layout/activity_main.xml

Add java code


If you have a button with id in XML file like above second button of activity_main.xml file, your java code looks like this.
Button button = (Button) findViewById(R.id.second_button_onclick);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // This Perform action on click
                Intent intent = new Intent(view.getContext(), SecondActivity.class);
                startActivity(intent);
            }
        });
Instead of this, you can handle click by adding onClick attribute in your XML file like in the first button of activity_main.xml file and your java code will look like this.
public void firstButtonClick(View v) {
        Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
    }
I think this method is simple to use and easy to understand.

If you face problem to implement above two methods to handle on click in android button, look at the code given below. Here, I have provided other all necessary XML and Java file code.

Complete code of MainActivity.java file looks like this.
src/MainActivity.java

Create a new SecondActivity.java and a second_activity.xml file which are following.
src/SecondActivity.java

res/layout/second_activity.xml

And modified code of AndroidManifest.xml like this.

Finally, you have done. Run your Android Button onClick application which looks like this.

Android Button onClick

Download Complete Example Project

Download complete Android Button onClick project source code from GitHub.

Post a Comment

Powered by Blogger.