我想创建一个菜单项,当点击该项时,他将暂时消失。作为一个例子:我做了一个菜单GpsOn和GpsOff,如果GpsOn点击,那么他会消失,而唯一剩下的GpsOff,反之亦然。是否有任何教程或代码可以帮助我??
我的代码:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
if(isGpsOn){menu.getItem(MENU_GpsOn).setVisible(false);menu.getItem(MENU_GpsOff).setVisible(true);}
else { menu.getItem(MENU_GpsOn).setVisible(true);menu.getItem(MENU_GpsOff).setVisible(false);}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
switch (item.getItemId()) {
case MENU_Secure:
try {
sendSMS(name, "secure");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return(true);
case MENU_Unsecure:
try {
sendGPS(name, "notsec");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return(true);
case MENU_GpsOn:
try {
sendMobil(name, "gps on");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
isGpsOn=true;
// ((MenuItem)findViewById(MENU_GpsOff)).setVisible(false);
return(true);
case MENU_GpsOff:
try {
sendGPSOff(name, "gpsoff");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
isGpsOn=false;
return(true);
}
return(super.onOptionsItemSelected(item));
}
答案 0 :(得分:1)
试试这个,
public boolean checkHide = false
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case GPS:
if(checkHide){
checkHide=false;
item.setTitle("GPS_ON");
// ToDo your function
}
else{
checkHide=true;
item.setTitle("GPS_OFF");
// ToDo your function
}
}
答案 1 :(得分:0)
我认为你需要的是Toggle Button。要创建一个此类button,请查看此{3}},以及here和this one。
当然,如果我正确理解您的要求,