登录/退出时隐藏选项菜单中的菜单

时间:2016-11-03 15:01:17

标签: android eclipse menu sharedpreferences optionmenu

我有一个带有pref菜单的登录注销会话的应用程序。 我想当用户登录时,选项菜单只显示退出菜单。但是当用户注销时,选项菜单只显示登录菜单。我已经尝试了一些例子但在我的情况下总是给我一个主要的错误。

这是我的main.xml

    <item
            android:id="@+id/Login"
            android:orderInCategory="100"
            android:showAsAction="never"
            android:title="@string/Login">
  </item>

 <item 
           android:id="@+id/Logout" 
           android:title="Logout" />

这是我的config.Java

public class Config {
//URL to our login.php file
public static final String LOGIN_URL = "http://www.kinandayu.com/login.php";

//Keys for email and password as defined in our $_POST['key'] in login.php
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";

//If server response is equal to this that means login is successful
public static final String LOGIN_SUCCESS = "success";

//Keys for Sharedpreferences
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";

//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";

//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}

这是我在MainActivity.java中的选项菜单

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
        case R.id.Login:
            Intent a = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(a);
            return true;
        case R.id.Logout:
            logout();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }

在我的情况下,任何人都可以帮助我,每个答案对我都有帮助。

提前致谢

2 个答案:

答案 0 :(得分:0)

创建菜单布局:

public boolean onCreateOptionsMenu(Menu menu) {
    if(LOGGED_IN){
         getMenuInflater().inflate(R.menu.logout, menu);
    }else{
         getMenuInflater().inflate(R.menu.login, menu);
    }
    return true;
}

在充气菜单之前,只需检查登录会话的状态

答案 1 :(得分:0)

.vsix