One activity to another activity using Android Studio

When we are using one activity we want to move another activity so that one is one of the main part of any application.

We are here to show you how we can move from one activity to another activity while using android studio

Step 1 : res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Activity 1" />


<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:layout_centerHorizontal="true"
    android:text="open activity 2" />

</RelativeLayout>

Step 2 : create new empty activity “Activity2”

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity2">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Activity 2" />

</RelativeLayout>

Step 3 : java/MainActivity

public class MainActivity extends AppCompatActivity {
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openActivity2();
        }
    });
}

public void openActivity2() {
    Intent intent = new Intent(this, Activity2.class);
    startActivity(intent);
 }
}

That’s it, friends, this is the correct and simple way to move from one activity to another activity in your application. Just follow the above steps and copy paste code carefully at the correct location mentioned above.

if you found this article helpful please do comment below and share the article to support me. if you have any suggestion please feel free to comment below.

Leave a Comment

Your email address will not be published. Required fields are marked *