How to open new activity on button click in Android studio




How to go a new activity on button click in android studio:
--------------------------------------------------------------------------

In main activity take a button. Cast this button. set onClickListener. write Intent in the method.
You've to know about the intent.


An Intent is exactly what it describes. It's an "intention" to do an action.An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react according



How to write Intent:
-----------------------------------

Intent i = new Intent(MainActivity.this,SecondActivity.class);

startActivity(i);



How to show Toast message in android studio:
------------------------------------------------------------------------------------

Toast.makeText(SecondActivity.this," Write toast message here",Toast.LENGTH_SHORT).show();



First You have to minimum 2 activity files




here  you can see 2 files in java folder and layout folder

activity_main.xml



Full Code: activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context="com.example.hp.symonapps.MainActivity"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/j">



    <Button
        android:id="@+id/btnSecond"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to Second Activity"
        android:layout_gravity="center"/>

</LinearLayout>




MainActivity.java



Full Code:  MainActivity.java
----------

package com.example.hp.symonapps;


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.Toast;



public class SecondActivity extends AppCompatActivity {



    Button m;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_second);



        m = (Button)findViewById(R.id.btnSecond);


        m.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {



                startActivity(new Intent(MainActivity.this,SecondActivity.class));



                Toast.makeText(SecondActivity.this,"Lets go to SecondActivity",Toast.LENGTH_SHORT).show();



            }

        });







    } //onCreate end

}




Comments