Set Initial Fragment on startup

前端 未结 2 938
滥情空心
滥情空心 2020-12-20 07:04

I am trying to set which fragment should be displayed first on start up. To determine this I check whether the user is logged in with ParseUser.getCurrentUser() and if a fil

2条回答
  •  情话喂你
    2020-12-20 07:57

    Write this in the onCreate(Bundle savedInstanceState) method after you set your drawer up:

    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
    
    if (savedInstanceState == null) {
        // on first time to display view for first navigation item based on the number
        onSectionAttached(2); // 2 is your fragment's number for "CollectionFragment"
    }
    

    Notice that your Fragment's number is 2. The number is got from your public void onSectionAttached(int number) method. If case 2: opens the CollectionFragment, so your Fragment's number is 2 (because of case number is 2). Then, alter your onSectionAttached() slightly:

    public void onSectionAttached(int number) {
        // update the main content by replacing fragments
        Fragment fragment = null;
    
        switch (number) {
            case 1:
                mTitle = "Home";
                break;
            case 2:
                mTitle = "My Information";
                fragment = new CollectionFragment();
                break;
            case 3:
                mTitle = "My Display";
                fragment = new Display();
                break;
            case 4:
                mTitle = "Donate";
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.org"));
                startActivity(browserIntent);
                break;
            case 5:
                mTitle = "Settings";
                break;
            case 6:
                mTitle = "Log Out";
                ParseUser.logOut();
                fragment = new Authentication();
                break;
            default:
                break;
            }
    
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment).commit();
    
            } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
    

    So now, you just need to call onSectionAttached(your fragment's number); to display your Fragment you want.

提交回复
热议问题