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="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity" >
    <item android:id="@+id/menu_about_us"
        android:title="About Us"
        android:orderInCategory="100"
        app:showAsAction="never" />
    <item android:id="@+id/menu_our_webpage"
        android:title="Our Webpage"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>


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

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

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

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






As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles