How to open new Activity.

In my program when the user click on button it will open the new Activity.


Open New Activity:.

In this section i am going to show you open the new Activity with practical example.

First open the android studio and create a project and give the name of your project like OpenActivityDemo.

The screenshots of the program is as follows:

Smiley face Smiley face

Drag and drop the one Button from pallet. Open the activity_main.xml file and code look like this


<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="com.example.niitpc.myapplication.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:gravity="center"
        android:layout_marginLeft="150dp"
        android:onClick="onClickButton"
        android:text="Next" />
</RelativeLayout>


     

Take a new activity for this you right click on the app folder and a pop menu display click new->Activity->Empty Activity. A dialog box will open you can change the Activity Name but directly click on finish.

This will create the Empty Activity and simple drag and drop TextView from pallet and set the property android:Text="Welcome to this page".

Open the MainActivity.java file and write code look like this.


package com.example.niitpc.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

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

    }
    public void onClickButton(View v)
    {

           Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(intent);
    }
}

Explanation:

Intent intent=new Intent(getApplicationContext(),Main2Activity.class):In this statement i am going to create the object of Intent and Intent constructor take two argument current context and the Activity that you want to open. In my case i want to open the Main2Activity.Do not forgot the Write like this Main2Activity.class .

startActivity(intent):The startActivity() take the Intent that you want to start as argument.


Open New Activity

What is open new activity for video Click here

Smiley face                     Smiley face