Search code examples
androidandroid-fragmentsfragmenttransaction

Where to put fragment transaction?


I wish to show the homefragment once the application launched, means before the menuitem clicked, where should i put the fragment transaction? thanks!

    public boolean onOptionsItemSelected(MenuItem item) {
     // The action bar home/up action should open or close the drawer.
     // ActionBarDrawerToggle will take care of this. 

    switch(item.getItemId()){
    case android.R.id.home:
        if(mDrawerLayout.isDrawerOpen(leftDrawerLayout)){
            mDrawerLayout.closeDrawer(leftDrawerLayout);
        } else {
            mDrawerLayout.openDrawer(leftDrawerLayout);
        }
    case R.id.home:
        Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_LONG).show();
        **ft.replace(R.id.content_frame, homefragment);**
        break;

    case R.id.feed:
        Toast.makeText(getApplicationContext(), "feed", Toast.LENGTH_LONG).show();
        ft.replace(R.id.content_frame, feedfragment);
        break;
    }
    ft.commit();
    return super.onOptionsItemSelected(item);

}

Solution

  • Try this..

    case R.id.home:
        Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_LONG).show();
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ClassName homefragment = new ClassName();
        ft.replace(R.id.content_frame, homefragment);
        ft.commit();
        break;
    
    case R.id.feed:
        Toast.makeText(getApplicationContext(), "feed", Toast.LENGTH_LONG).show();
    
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ClassName feedfragment = new ClassName();
        ft.replace(R.id.content_frame, feedfragment);
        ft.commit();
        break;