Android Button OnClickListener Tutorial

Опубликовано: 06 Ноябрь 2024
на канале: Coding Demos
20,251
175

In this tutorial you will learn how to use a button OnClickListener and make it clickable to open another activity by using intent. Here is how to do it:

Open activity_main.xml file and then remove the hello world textview
and replace it with a button

Give the button a label and we call it (Hello World) like this: android:text="Hello World"

Now we need to position the button to the top-center of the screen like this:
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"

Next open up MainActivity.java and here is where we will declare the button as follows:
Button mButton = (Button) findViewById(R.id.button);

To make the button clickable and perform an action we need to call setOnClickListener like this:
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

}
});

Now we have the button and it's clickable but it doesn't do any action, and what we really want is once the user who taps on the button will move to another page, so first we need to create an activity and resource file so that it will act as the second page like this:
click on File – New – Activity – Empty Activity then you give a name for the activity and the resource file.

Once we have created the second activity, now we can work on the button setOnClickListener part to allow the user to move to another page.
This can be done like this:
startActivity(new Intent(MainActivity.this, SecondActivity.class));
MainActivity.this will be the current activity and starting point while the SecondActivity.class will like the destination

That's it :)

Source code: https://github.com/codingdemos/DemoBu...