- Java code
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main);} /*创建menu*/public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); //设置menu界面为res/menu/menu.xml inflater.inflate(R.menu.menu, menu); //inflater. return true;}
这是Activity中的代码
- XML code
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/about" android:title="关于" /> <item android:id="@+id/exit" android:title="退出" /></menu>
这是XML代码,但是运行之后模拟器屏幕不显示菜单。。。。。。。。。。。
------解决方案--------------------
在setContentView(R.layout.activity_main);下面加入以下代码:
- Java code
LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setBackgroundColor(Color.RED); linearLayout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); Button button = new Button(this); button.setText("显示菜单"); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub openOptionsMenu(); } }); linearLayout.addView(button); addContentView(linearLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));