问题 1:对于所有其他活动,我可以使用相同的 menu.xml 文件,但我是否需要覆盖每个活动的 onCreateOptionMenu 函数。
是的,只需添加代码来处理 switch 语句中的菜单选项。
问题 2:我需要在所有活动中编写 onOptionItemSelected 功能代码吗?
是的,对于每个使用操作栏的活动,您需要覆盖 onOptionItemSelected 函数并添加您的自定义代码。
例如:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_watchlist:
Intent intent = new Intent(HomeActivity.this, WatchlistActivity.class);
intent.putExtra("username", currentUser.getUsername());
startActivityForResult(intent, 0);
return true;
case R.id.menu_history:
Intent intent2 = new Intent(HomeActivity.this, HistoryActivity.class);
intent2.putExtra("username", currentUser.getUsername());
startActivityForResult(intent2, 0);
return true;
case R.id.menu_scores:
// Scores only available with Facebook login
if (facebookLogin)
{
Intent scoreIntent = new Intent(HomeActivity.this, ScoresActivity.class);
scoreIntent.putExtra("username", currentUser.getUsername());
scoreIntent.putExtra("accessToken", accessToken);
Session session = Session.getActiveSession();
scoreIntent.putExtra("session", session);
startActivityForResult(scoreIntent, 0);
}
else
Toast.makeText(getApplicationContext(), "Please login to Facebook to use this feature.", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_settings:
Intent intent3 = new Intent(HomeActivity.this, SettingsActivity.class);
intent3.putExtra("username", currentUser.getUsername());
startActivityForResult(intent3, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}