Android Intent from one activity to other

An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

1. Consider two activities called Activity1 and Activity2 are created. If there is a need to goto second activity from first activity, then Intent class is used.

2. Create a button in the first activiy

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

3. Set an OnClickListener for it

b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //todo code
            }
        });

4. Inside the onClick method create an Intent object

Intent obj = new Intent(Activity1.this,Activity2.class);

5. Start that activity by calling startActivity method

startActivity(obj);


The complete coding will be


package com.nishanth;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.widget.Button;

public class Activity1 extends AppCompatActivity {

Button b1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        b1 = (Button)findViewById(R.id.push_button2);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent obj = new Intent(Activity1.this, Activity2.class);
                startActivity(obj);
            }
        });

    }

}

Output


Powered by Blogger.