Saturday, October 4, 2014

Android: opening other screen (Activity) from Menu

In this tutorial you will learn how to open a new screen (Activity) using an Intent and Menu items.

Step 1: Define items in your menu/main.xml

<menu xmlns:android=""
    tools:context=".MainActivity" >
    <item android:id="@+id/menu_about_us"
        android:title="About Us"
        app:showAsAction="never" />
    <item android:id="@+id/menu_our_webpage"
        android:title="Our Webpage"
        app:showAsAction="never" />

Step 2: Add constants for any message names you will want to send

public class MainActivity extends FragmentActivity {

   private static String TAG = MainActivity.class.getSimpleName();
   public final static String EXTRA_MESSAGE = MainActivity.class.getPackage() + "MESSAGE";

Step 3: Open new Activity depending on selection

   public boolean onOptionsItemSelected(MenuItem item) {
      // menu items are defined in menu/main.xml
      switch (item.getItemId()) {
         Intent intent = new Intent(this, AboutUs.class);         intent.putExtra(EXTRA_MESSAGE, "from main Activity");
         startActivity(intent);         Log.d(TAG, "Menu: About Us selected");
         // TODO implement our web page Activity
         Log.d(TAG, "Menu: Our Web page selected");
      return super.onOptionsItemSelected(item);

Step 4: Finally, when you open the new Activity you can receive the message.

public class AboutUs extends ActionBarActivity {
   protected void onCreate(Bundle savedInstanceState) {
      TextView text = (TextView) findViewById(;
      Intent intent = getIntent();
      String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
      text.setText("This is About Us page with message from Main activity: " + message);