在导航抽屉项目上切换片段单击

时间:2015-01-14 14:08:00

标签: java android android-fragments navigation-drawer

我在我的应用程序中使用导航抽屉并实现了在NavigationDrawerFragment类中切换片段的逻辑。我最近读到片段切换只能从托管活动中发生。

有一个从NavigationDrawerFragment调用的接口,用于在导航抽屉列表视图中通知MainActivity所选位置。

public static interface NavigationDrawerCallbacks {
    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
} 

我感到困惑的是,MainActivity中有一个静态片段,它使用NavigationDrawerFragment中接口提供的位置进行调用。

@Override
public void onNavigationDrawerItemSelected(int position) {

    FragmentManager fragmentManager = getFragmentManager(); 
    fragmentManager
            .beginTransaction()
            .replace(R.id.container,
                    PlaceholderFragment.newInstance(position)).commit();

}

PlaceHolderFragment类如下所示:

public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static Fragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();

        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MCMainActivity) activity).onSectionAttached(getArguments()
                .getInt(ARG_SECTION_NUMBER));
    }
}

目前我的片段交易发生如下:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView
            .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    selectItem(position);
                    Fragment fragment;
                    FragmentManager fManager = getFragmentManager();

                    int count = fManager.getBackStackEntryCount();
                    for (int i = 0; i < count; ++i) {

                        fManager.popBackStackImmediate();
                        Log.e("NavFrag", "Popped frag" + i);
                    }
                    FragmentTransaction fTransaction = fManager
                            .beginTransaction();
                    switch (position) {
                    case 0:
                        fragment = new MCTrackFragment();
                        fTransaction.replace(R.id.container, fragment)

                                .commit();
                        break;
                    case 1:
                        fragment = new MCPlaylistFragment();
                        fTransaction.replace(R.id.container, fragment)
                                .commit();
                        break;
                    case 2:
                        fragment = new MCOfflineSongs();
                        fTransaction.replace(R.id.container, fragment)
                                .commit();
                        break;
                    case 3:
                        fragment = new MCOwnFeed();
                        fTransaction.replace(R.id.container, fragment)
                                .commit();
                        break;
                    case 4:
                        fragment = new MCCategories();
                        fTransaction.replace(R.id.container, fragment)
                                .commit();
                        break;
                    }
                }
            });
    mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar()
            .getThemedContext(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1, new String[] {
                    getString(R.string.title_section1),
                    getString(R.string.title_section2),
                    getString(R.string.title_section3),
                    getString(R.string.title_section4),
                    getString(R.string.title_section5) }));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

当我们使用navigationdrawer创建项目时,会自动生成占位符片段。

什么是占位符片段?

如何使片段事务在托管这些片段的Activity中发生?

我尝试在接口实现中添加片段事务,但它无法正常工作。

提前感谢,感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我们需要始终从活动切换片段是正确的,因此我们需要提供从导航抽屉片段到要承载要显示的新片段的活动的回调。 在活动内部,切换片段的代码如下:

@Override
public void onNavigationDrawerItemSelected(int position) {

    Fragment fragment;
    FragmentManager fManager = getFragmentManager();
    Bundle args = new Bundle();
    args.putInt(MCConstants.ARG_SECTION_NUMBER, position);
    clearAllBackStack();
    FragmentTransaction fTransaction = fManager.beginTransaction();
    if (MCMediaPlayerService.getInstance() != null) {
        MCMediaPlayerService.getInstance().stopMusic();

    }
    MCSelectedTrackIdSingleton.getInstance().mCurrentSongId = 0;
    MCSelectedSongIdSingleton.getInstance().mCurrentSongId = 0;

    switch (position) {
    case 0:
        fragment = new MCTrackFragment();
        fragment.setArguments(args);
        fTransaction.replace(R.id.container, fragment,
                MCConstants.TRACK_TAG).commit();
        break;
    case 1:
        fragment = new MCPlaylistFragment();
        fragment.setArguments(args);
        fTransaction.replace(R.id.container, fragment,
                MCConstants.PLAYLIST_TAG).commit();
        break;
    case 2:
        fragment = new MCOfflineSongs();
        fragment.setArguments(args);
        fTransaction.replace(R.id.container, fragment,
                MCConstants.OFFLINE_TAG).commit();
        break;
    case 3:
        fragment = new MCOwnFeed();
        fragment.setArguments(args);
        fTransaction.replace(R.id.container, fragment,
                MCConstants.OWNFEED_TAG).commit();
        break;
    case 4:
        fragment = new MCCategories();
        fragment.setArguments(args);
        fTransaction.replace(R.id.container, fragment,
                MCConstants.CATEGORIES_TAG).commit();
        break;
    }

}

导航抽屉片段类的onCreate方法内部:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Read in the flag indicating whether or not the user has demonstrated
    // awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState
                .getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition); //Select item called
}

选择项目方法如下所示:

 private void selectItem(int position) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
}