如何在每次打开应用程序时调用片段?

时间:2018-01-14 14:05:34

标签: android android-fragments

我有一个导航抽屉,但主要活动什么都没有,只有主页面片段有一些东西,我想每次打开应用程序时调用这个片段。任何人都知道如何做到这一点?

这是一个例子

enter image description here

1 个答案:

答案 0 :(得分:0)

如下面的代码所示,请在代码onNavigationItemSelected(nvDrawer.getMenu().getItem(0));

中添加此行
public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            // ...From section above...

            // Find our drawer view

            nvDrawer = (NavigationView) findViewById(R.id.nvView);

            // Setup drawer view

            setupDrawerContent(nvDrawer);
            selectDrawerItem(nvDrawer.getMenu().getItem(0));
        }



        private void setupDrawerContent(NavigationView navigationView) {

            navigationView.setNavigationItemSelectedListener(

                    new NavigationView.OnNavigationItemSelectedListener() {

                        @Override

                        public boolean onNavigationItemSelected(MenuItem menuItem) {

                            selectDrawerItem(menuItem);

                            return true;

                        }

                    });

        }



        public void selectDrawerItem(MenuItem menuItem) {

            // Create a new fragment and specify the fragment to show based on nav item clicked

            Fragment fragment = null;

            Class fragmentClass;

            switch(menuItem.getItemId()) {

                case R.id.nav_first_fragment:

                    fragmentClass = FirstFragment.class;

                    break;

                case R.id.nav_second_fragment:

                    fragmentClass = SecondFragment.class;

                    break;

                case R.id.nav_third_fragment:

                    fragmentClass = ThirdFragment.class;

                    break;

                default:

                    fragmentClass = FirstFragment.class;

            }



            try {

                fragment = (Fragment) fragmentClass.newInstance();

            } catch (Exception e) {

                e.printStackTrace();

            }



            // Insert the fragment by replacing any existing fragment

            FragmentManager fragmentManager = getSupportFragmentManager();

            fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();



            // Highlight the selected item has been done by NavigationView

            menuItem.setChecked(true);

            // Set action bar title

            setTitle(menuItem.getTitle());

            // Close the navigation drawer

            mDrawer.closeDrawers();

        }

    }