在片段导航抽屉中切换视图时出错,表示找不到片段PlaceholderFragment的视图

时间:2015-07-08 10:18:25

标签: java android android-layout android-fragments android-activity

我使用导航抽屉片段通过Android Studio创建了一个简单的应用程序。

当用户点击layout_about.xml的项目时,我试图显示另一个视图(例如ListView)。

所以我在setContentView()中使用public void onNavigationDrawerItemSelected(int position)但是当我运行它时,发生了错误:

FATAL EXCEPTION: mainProcess: com.akakanch.sample, PID: 28848
    java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 (com.akakanch.sample:id/container) for fragment PlaceholderFragment{250d0b42 #1 id=0x7f0c0050}

这是我唯一改变的地方:

MainActivity.java

 @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
        setContentView(R.layout.layout_about);


    }

那么,我该如何正确更改视图?

1 个答案:

答案 0 :(得分:0)

试试这个:

private void setUpSlideMenu() {
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            //close if the selected item equals current fragment
            if (mCurrentNavItem == item.getItemId()) {
                mDrawerLayout.closeDrawers();
                return true;
            }
            switch (item.getItemId()) {
                case R.id.drawer_menu_about:
                    break;
                case R.id.drawer_menu_browser:
                    setFragment(new BrowserFragment());
                    break;
                case R.id.drawer_menu_library:
                    setFragment(new LibraryFragment());
                    break;
            }
            //save selected id
            mCurrentNavItem = item.getItemId();
            item.setChecked(true);
            mDrawerLayout.closeDrawers();
            return true;
        }
    });
}

setFragment:

//pop all and set a new fragment
private void setFragment(Fragment fragment) {
    if (mFragmentManager.getBackStackEntryCount() > 0) {
        //pop all fragment
        mFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    mFragmentManager.beginTransaction()
            .replace(R.id.content_frame, fragment)
            .commit();
}