Android 如何在片段的OnOptions ItemSelected中调用自定义类

Android 如何在片段的OnOptions ItemSelected中调用自定义类,android,android-fragments,Android,Android Fragments,如何在OnOptions ItemSelected方法中调用自定义类。我有片段,有些片段有不同的actionbars项目。我不想一次又一次地编写相同的代码item.getItemId。我为操作栏选定的项编写了一个关于的类。它不起作用。如何调用自定义类和方法 public class ActionMenuItemSelected { public Fragment actionMenuSelectedItem(MenuItem item) { Fragment select

如何在OnOptions ItemSelected方法中调用自定义类。我有片段,有些片段有不同的actionbars项目。我不想一次又一次地编写相同的代码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,我想在片段的OnOptions ItemSelected方法中调用这个方法。我做不到。您能帮我调用此方法吗?

在活动中,您需要对菜单布局进行充气

//Add this method to your activity
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu); // Inflate your menu
    return true;
}
设置菜单布局后,可以调用自定义类

私有最终操作MenuItemSelected amis=新操作MenuItemSelected

但是,如果应用程序中只有一个活动具有此菜单设置,则可以将所有ActionMenuItemSelected.actionMenuSelectedItemlogic放入OnOptions ItemSelectedMenu项方法中

别忘了调用SetHasOptions菜单;如果您在片段中,请使用onCreate方法

public boolean onOptionsItemSelected(MenuItem item) {        
    Fragment frag = amis.actionMenuSelectedItem(item);
    goToFragment(frag); // assuming that this method is in your class Activity 
    return true;
}