0

我想为该项目创建一个菜单,单击该项目时,他将暂时消失。举个例子:我做了一个菜单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));
 }
4

2 回答 2

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
                 }
}
于 2013-07-02T05:49:31.197 回答
0

我认为您需要的是Toggle Button。要创建一个这样的按钮,请在此处查看这个 tut以及这个这个

当然,如果我正确理解了您的要求。

于 2013-07-02T05:31:53.017 回答