I am trying to create a menu demo, but I am unable to see the menu. The only thing I can see is the "TextView" view in the layout. Below is the code:
menu.xml in (res\menu)
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:title="@string/new_game"
android:id="@+id/new_game">
</item>
<item
android:title="@string/quit"
android:id="@+id/quit"
>
</item>
</group>
</menu>
demomenu.java
package com.test.demomenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class demomenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
//super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the item", Toast.LENGTH_LONG).show();
return true;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, demomenu!</string>
<string name="app_name">Demo Menu</string>
<string name="new_game">New Game</string>
<string name="quit">Quit</string>
</resources>
When I run the project, I can only see the "TextView" and not t开发者_如何学运维he menu. I would appreciate it if someone can tell me what is wrong with the application.
I don't think you can have checkable items in an options menu. The documentation states:
Options menus: The icon menus do not support item check marks...
Try removing the group
tag and see if the menu will display.
You are using R.menu.game_menu
but you say your xml is named menu.xml
.
Do you get anything in the logcat? Have you tried to debug? Is onCreateOptionsMenu
called when you press the menu button?
Comparing you code to my tutorial I can't find a important difference.
Sid... try using LogCat.
So import
import android.util.*;
declare your TAG
private static final String TAG= "Sid";
Add debugging code to onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Log.d(TAG,"onOptionsItemSelectedCalled");
return true;
}
Run your app and press on the menu button. Now look into LogCat, after filtering for TAG:Sid and Log Level Debug, for the message tag:Sid Message:"onOptionsCalled".
JAL
精彩评论