Question

When using the Android Eclipse IDE, how do I add a menu that is triggered by the phone menu button such that it has to have an "About" choice that displays an "About my app" dialog and a "Quit" choice that exits the app?

Was it helpful?

Solution

To create a content menu with about a quit items, please add all of the following to your project after first removing any other attempts at an about menu that might potentially conflict with this code. Let Eclipse help you add the required imports or peruse the android documentation as you try to build this, and after everything's in place it should just work :-)

In /res create a folder menu containing a file main.xml with the following xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
  <item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/action_settings"/>
  <item
    android:id="@+id/action_quit"
    android:orderInCategory="101"
    android:showAsAction="never"
    android:title="@string/action_quit"/>
</menu>

In MainActivity.java add the following after your onCreate is closed:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.action_settings:
      AboutDialog about = new AboutDialog(this);
      about.setTitle(“About “my app);
      about.show();
      return true;
    case R.id.action_quit:
      System.exit(0);
      return true;
  }
}

Add a new java file but extend Dialog instead of Activity, like shown:

public class AboutDialog extends Dialog {
  public AboutDialog(Context context) {
    super(context);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.dialog_about);
  }
}

Finally, add a new layout dialog_about.xml like so:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/ScrollView01"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

</ScrollView>

Of course you’ll need to add another layout and content inside the ScrollView, and you may want other features in your menu and your quit item could use a confirmation (possibly). But this should get you started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top