how to move from one activity to another in android
Do you want to know how to move from one Activity to Another in Android?

Okay…Let’s go.



How to start new Activity using Intent in Android

In Android, we can use Intent to start another activity. Intent can be used to launch other app activities too. But now we simply describe starting a new activity.


this@MainActivity(MainActivity.this) – Here means Context, Activity is a subclass of Context.

That’s why we use this@MainActivity here. You can also use this, but assure that it’s a context.

SecondActivity::class.java(SecondActivity.this) – Name of Activity which you want to start.

Let’s dig more…

Two main parts here.

  • Intent(Context packageContext, Class cls) – Using this Intent’s constructor, we can create a way to our second activity.
  • startActivity(Intent intent) – It’s one of the methods in Activity class and launches activity specified in the Intent. If there is no Activity found, ActivityNotFoundException() gets called.

Intent needs a Java reference of class. That’s why We use here class.java part in Kotlin.

Create an Android Studio project

In this example, We just create two activities, when you click on the button, It shows Second Activity. Here I have used OnClickListener for click events, You can also use android:onClick”attribute.

Okay.

Open Android Studio and start a new Android Studio project.

Application name : Start New Activity Ex.

Company domain: androidride.com

Check to include Kotlin support.


Select minimum SDK:API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.

build.gradle(Project: StartNewActivityEx – Kotlin)

build.gradle(Module:app)

colors.xml

strings.xml

styles.xml

activity_main.xml

MainActivity.kt


Create Second Activity

Right-click on App-> New -> Activity -> Empty Activity ->

Activity Name: SecondActivity

check Generate Layout File.

Layout Name: activity_second

Select your source language Kotlin/Java.

and click Finish.

activity_second.xml

SecondActivity.kt

Run now.

launch new activity in android

This is so simple. Isn’t it?

If you found this article helpful. please share it.

Reference:

startActivity()

Intent class – google docs