Home Next Tutorial

How To open second activity from current activity in Android


Step 1: Open Android Studio
Step 2: Select File->New->New Project
Step 3: In the Create New Project window type Application Name as "IntentDemo" and click on Next button. In the Target Android Devices select Minimum SDK and click on Next Button. In The Add an Activity to Mobile select blank activity and click on Next Button.Click on Finish button.
Step 4: Design an activity as shown below:

Intent Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Activity"
android:id="@+id/btnClick"

android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Step 5: Select File->New->Activity->Blank Activity.Specify Name of Activity as "SecondActivity" and click on Finish Button. It will create second activity in your application.

Step 6: Open MainActivity.java file and write following code in the onCreate() method to open second activity from MainActivity.

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.btnClick);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,SecondActivity.class);
startActivity(i);
}
});
}

Step 6:Run the application.

Download Projects


Download Programs