0

Hy!

I want to make my first Menue

I just createt the folder /res/menu and the file menu.xml

Code:

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/quit"
          android:icon="@drawable/icon"
          android:title="Quit" />
</menu>

In my code i add:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.menu,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  Main.this.finish();
  return true;
}

If i start my app and press the menu button nothing appear.

Whats wrong?

user547995
  • 2,036
  • 8
  • 33
  • 62

3 Answers3

1

Okay, Instead of your second group of code, try using this instead: this will fix your problem because you need to use onCreateOptionsMenu instead of onCreateContextMenu

public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            return true;
        }

public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
         case R.id.quit: 
           finish();
           return true;
         default:
            return super.onOptionsItemSelected(item);
      }
}
Samuel
  • 4,337
  • 3
  • 29
  • 35
  • no problem, click the little check mark below the 1 to select this as your selected answer! – Samuel Dec 23 '10 at 22:12
  • on question: i have a thread which download every 3 seconds data from the inet but when i press close i think the thread is still alive? any solution? – user547995 Dec 23 '10 at 22:30
  • try this http://stackoverflow.com/questions/680180/where-to-stop-destroy-threads-in-android-service-class – Samuel Dec 23 '10 at 23:01
0

First you need to override onCreateOptionsMenu() insteald of onCreateContextMenu() and secondly, in the onOptionsItemSelected() you should do the following:

@Overrid
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.[your desired item id here]:
            //do what you want to do for this item!
        break;
    }
    return true;
}

Hope that helps!

biegleux
  • 13,179
  • 11
  • 45
  • 52
samser
  • 83
  • 6
0

You are doing things in onCreateContextMenu. This is the menu that comes up when you long press To add things to the menu you get hitting the menu button, you want to do them in onCreateOptionsMenu.

Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82