【问题标题】:Switching fragments on Navigation Drawer item click在导航抽屉项目单击上切换片段
【发布时间】:2015-01-14 14:07:59
【问题描述】:

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

有一个从 NavigationDrawerFragment 调用的接口,用于通知 MainActivity 在 Navigation Drawer 列表视图中被选中的位置。

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 中发生?

我尝试在接口实现中添加片段事务,但它不起作用。

感谢您的帮助,在此先感谢

【问题讨论】:

    标签: java android android-fragments navigation-drawer


    【解决方案1】:

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

    @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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多