您的位置:首页 > 移动开发 > Android开发

android menu的使用(Menu无法弹出问题)

2011-10-27 10:25 260 查看
1.在主Activity中覆盖onCreateOptionsMenu(Menu menu)方法。

/ 创建菜单

public boolean onCreateOptionsMenu(Menu menu) {

// TODO Auto-generated method stub

super .onCreateOptionsMenu(menu);

menu.add(0, Menu. FIRST + 1, 1, " 打开 GPS 监控 " );

menu.add(0, Menu. FIRST + 2, 2, " 关闭 GPS 监控 " );

return true ;

}

2.这样就有了两个菜单选项。如果要添加点击事件,则要覆盖onOptionsItemSelected(MenuItem item)方法。

// 菜单项监听

public boolean onOptionsItemSelected(MenuItem item) {

Intent i;

// TODO Auto-generated method stub

super .onOptionsItemSelected(item);

switch (item.getItemId()) {

case Menu. FIRST + 1: // 打开 GPS 监控

this .setTitle( "GPS已经打开" );

i = new Intent(PhoneSoftActivity.this , GpsService.class );

this.bindService(i,connection,Context.BIND_AUTO_CREATE );

break ;

case Menu. FIRST + 2: // 关闭 GPS 监控

this .setTitle( "GPS已经关闭" );

// 通过检测 mBinder 是否为空来判断服务是否已绑定,从而避免 service not registered 错误

if ( mBinder != null ){

i = new Intent(this , GpsService.class );

this .unbindService( connection );

mBinder=null;//释放mBinder,防止重复解绑定

}

break ;

}

return true ;

}

更多的应用请baidu。网上很多。主要记录下 点击Menu按钮菜单不弹出的一个问题。

如果程序监听按键 如返回键等 如下

long exitTime = 0;

public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

if ((System.currentTimeMillis() - exitTime) > 2000) {

Toast.makeText(getApplicationContext(), "再按一次退出程序",

Toast.LENGTH_SHORT).show();

exitTime = System.currentTimeMillis();

}

else {

//finish();

//System.exit(0);

ActivityManager activityMgr=(ActivityManager)this.getSystemService(ACTIVITY_SERVICE);

activityMgr.restartPackage(getPackageName());

PhoneSoftActivity.this.finish();

}

}

return true;

}

点击Menu按键就无法弹出菜单。加入下面代码解决

public boolean onKeyUp(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_MENU) {

super.openOptionsMenu();

}

return true;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐