Tutorial how to create second activity in Android Studio
Create second activity and connect it with main activity with a button click and and vice versa in Android Studio version 3.1.3.
Create new project with Application name: Start Another Activity; Minimum SDK: API 21 – Android 5.0 (Lollipop).
In app->java->MainActivity.java write the code:
package com.app.toyo.startanotheractivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.button1);
v.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.button1) {
//define a new Intent for the second Activity
Intent intent = new Intent(this, SecondActivity.class);
//start the second Activity
this.startActivity(intent);
}
}
}
In app->res->layout->activity_main.xml write the code:
In app->java create New -> Java Class: SecondActivity.java and write the code:
package com.app.toyo.startanotheractivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
View v = findViewById(R.id.button2);
v.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.button2) {
//define a new Intent for the second Activity
Intent intent = new Intent(this, MainActivity.class);
//start the second Activity
this.startActivity(intent);
}
}
}
In app->res->layout create New -> Layout resource file: activity_second.xml and write the code:
<resources>
<string name="app_name">Start another activity</string>
<string name="button1">CLICK</string>
<string name="button2">BACK</string>
</resources>
Run app in mobile device or Emulator (API 21–Android 5.0) and switch between main activity and second activity with buttons.
Follow VideoTutorial:
Download project with Source Code from here:
https://android-coffee.com/wp-content/uploads/projecs/Startanotheractivity.7z
Please subscribe here to our YouTube channel. Thank you!
Check next tutorials to learn all about Android.
For furtherquestionsleave a message.
Leave a Reply