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="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);
   }