如何在onOptionsItemSelected方法中调用自定义类。我有片段,有些片段具有不同的操作栏项目。我不想一遍又一遍地写相同的代码item.getItemId()
。我写了一个关于操作栏所选项目的类。它不起作用。如何调用自定义类和方法?
public class ActionMenuItemSelected {
public Fragment actionMenuSelectedItem(MenuItem item) {
Fragment selected_fragment = null;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
switch (item.getItemId()) {
case R.id.action_menu_Resmece:
selected_fragment = new MainFragment();
break;
case R.id.action_menu_account:
selected_fragment = new AccountFragment();
break;
case R.id.action_level_about_us:
selected_fragment = new AboutUsFragment();
break;
case R.id.action_level_contact_us:
selected_fragment = new ContactUsFragment();
break;
case R.id.action_menu_log_out:
mAuth.signOut();
selected_fragment = new RegisterFragment();
Toast.makeText(getApplicationContext(), "Logged out", Toast.LENGTH_SHORT).show();
break;
}
return selected_fragment;
}
//region goToFragment
public void goToFragment(Fragment selectFragment) {
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.main_frame, selectFragment).addToBackStack(null).commit();
}
//endregion
}
我添加了一个类名ActionMenuItemSelected,我想在片段的onOptionsItemSelected方法中调用此方法。我做不到您能帮我调用这种方法吗?
答案 0 :(得分:1)
在“活动”中,您需要增加菜单布局
Perl
设置菜单布局后,您可以调用自定义类
//Add this method to your activity
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu); // Inflate your menu
return true;
}
private final ActionMenuItemSelected amis = new ActionMenuItemSelected();
但是,如果在您的应用程序中只有一个活动具有此菜单设置,则可以将所有public boolean onOptionsItemSelected(MenuItem item) {
Fragment frag = amis.actionMenuSelectedItem(item);
goToFragment(frag); // assuming that this method is in your class Activity
return true;
}
逻辑放入您的ActionMenuItemSelected.actionMenuSelectedItem
方法中。
如果您位于片段中,请不要忘记在onCreate()方法中调用onOptionsItemSelected(Menu item)