Tuesday 26 March 2013

How to redirect from one Activity to another in Android

This is my first post on Android Platform. I like to share my Android knowledge to all through this blog. Happy Learning

You need to use Intent Class in order to redirect from one activity class to another activity class.

Let's demonstrate this by providing an example. In this example, We will be displaying a 'show setting' menu in the action bar, by clicking on that, you will be redirect to another Activity

import android.app.Activity;

import android.os.Bundle;

import android.content.Intent;

import android.view.Menu;

import android.view.MenuItem;

public class MyActivity extends Activity {

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

  }

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

       menu.add(Menu.NONE, 0, 0, "show setting");

       return super.onCreateOptionsMenu(menu);

  }

  @Override

  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

     case 0:

      Intent show = new Intent(this, MenuActivity.class);

      startActivity(show);

      return true;

    }

    return false;

  }

}

onOptionsItemSelected() Method will be trigged when you click the 'show setting' menu in the action bar. 'show setting' menu item index is set as '0', this will match the switch case statement present inside onOptionsItemSelected method.

We need to pass 2 parameters to the Intent Class
  •  Current/Source Activity Class (you can use 'this' to refer current activity class)
  •  Destination Activity Class Name
 startActivity() is used to launch a new activity  or get an existing activity to do something new.

 Hope, you enjoyed this Post.

1 comment:

  1. Nice Tutorial, I tried in my application it works great ...

    ReplyDelete