Starting Another activity in Android

To start another activity simply means communications between different activities this is done by using intents. What are intents?

Intents are basically an description of an operation to be performed. It can be used for starting another activity, to launch another activity, to use BroadcastReceiver components, and to communicate with a background Services.

Step: 1

Just create a simple Button ,pressing that button will take us to the next activity.

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click to go in next activity"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:id="@+id/next"
        android:onClick="showmsg"
        />

 

Step 2:

Now create a new Activity by simply navigating through 1:Project>app>java>com.example.yourActivity>

now right click on this folder and go to new>activity>empty activity. Now click next to create a new activity.

Step 3:

Now we will assign task to our button to start another activity. Check out below code

public class MainActivity extends AppCompatActivity {

    Button b1;

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

        b1=(Button)findViewById(R.id.next);


    }
    public void showmsg(View view){
      Intent intent =new Intent(this, Main2Activity.class);
      startActivity(intent);
    }
}

Here in showmsg function we have created an intent in which we have passed the parameter ‘this‘ which is reference to current activity and and .class parameter of our newly created activity.

After that we have called function startActivity(intent) to start the activity.

Adding navigation to go back always important , which we will cover in further posts.

 

 

About kaushal97

Android Enthusiast

Leave a Reply

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