In this short Android tutorial I am going to share with you how to start a new Activity when Button is clicked.
To be able to follow this tutorial you will need to have an Android project created. I have created a very simple project with one MainActivity.
Add Button to Main Activity
To add Button in Android project, I will open the XML layout of MainActivity.java (activity_main.xml) and add the following lines:
<Button
android:id="@+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Click Button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Next, I will add the Button to MainActivity.java file and set an OnClickListener.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonOne = findViewById(R.id.buttonOne);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("Button Clicked");
}
});
}
}
Now, if I run this Android application I should be able to tap on a Button and see a “Button Clicked” message printed in Logcat console.
Create and Start New Activity
Using your Android Studio create a new Android Activity for your project. I will create a new Activity and call it Activity2.java.
To create and start a new activity I will use the following code snippet.
Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class); startActivity(activity2Intent);
Start New Activity on Button Click
Now let’s put the above code snippets together, so that a second activity is started when user taps on a Button.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonOne = findViewById(R.id.buttonOne);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("Button Clicked");
Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2Intent);
}
});
}
}
I hope this short Android tutorial was helpful. If you are looking for video lessons that teach Android step-by-step, have a look at the list of below video lessons. One of them might greatly help you learn Android App Development.