我有一个简单的要求,我在操作栏菜单中有 2 个菜单项。第一个用于使用谷歌帐户登录,第二个用于注销。我想根据用户的状态隐藏一个选项。即,如果用户已登录,我想隐藏其选项,并且当他/她注销时隐藏注销选项。问题是登录成功后我仍然看到登录选项。但是当我再次单击登录时,一切正常。即我看到注销选项。我还在登录时使用了 invalidateOptionsMenu() 但菜单第一次没有刷新。但是注销就像一个魅力。这是我的代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
MenuItem login = menu.findItem(R.id.action_login);
MenuItem logout = menu.findItem(R.id.action_logout);
if(account!=null) {
login.setVisible(false);
logout.setVisible(true);
} else {
login.setVisible(true);
logout.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, EditRssFeedActivity.class);
startActivity(intent);
return true;
} else if (id == R.id.action_login) {
signIn(mGoogleSignInClient);
greetUser();
invalidateOptionsMenu();
} else if(id == R.id.action_logout) {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
Toast.makeText(MainActivity.this,"User logged out",Toast.LENGTH_SHORT).show();
}
});
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void signIn(GoogleSignInClient mGoogleSignInClient) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MenuItem item = findViewById(R.id.action_login);;
if (requestCode == RC_SIGN_IN && item !=null) {
item.setVisible(false);
invalidateOptionsMenu();
greetUser();
}
}
有人可以帮我每次触发菜单刷新吗?