41

I know these types of question have already been here but still I have not found my answer for this question:

  • I have created an application and used navigation drawer that has been created AUTOMATICALLY by the app (AndroidStudio)

Here's what I have:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

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

public void onSectionAttached(int number) {
    switch (number) {
        case 1:

            break;
        case 2:

            break;
        case 3:

            break;
    }
}

And some more here:

    public static PlaceholderFragment 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);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

I want to display another fragment using the button in navigation drawer. I want to use this code so please do not send me any guides or tutorials making their own drawers..

The question is, what do I put in case 1: case 2: and case 3: in case I want to open another fragment? Thanks.

One more question:

  • How do I add more fragments and transactions? This doesn't work-

    Fragment fragment = new MyFragment1();
    Fragment frag = new MyFragment2();
    FragmentManager fragmentManager = getFragmentManager();
    switch(position) {
        case 0:
            fragment = new MyFragment1();
            break;
        case 1:
            frag = new MyFragment2();
    
            break;
    }
    fragmentManager.beginTransaction()
            .replace(R.id.container, fragment).commit();
    
danesh
  • 39
  • 6
user3053246
  • 733
  • 3
  • 8
  • 18

6 Answers6

68

You should just put a switch statement into the onNavigationDrawerItemSelected method.

Something like this should work:

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    Fragment fragment;
    FragmentManager fragmentManager = getFragmentManager(); // For AppCompat use getSupportFragmentManager
    switch(position) {
        default:
        case 0:
            fragment = new MyFragment1();
            break;
        case 1:
            fragment = new MyFragment2();
            break;
    }
    fragmentManager.beginTransaction()
        .replace(R.id.container, fragment)
        .commit();
}

This is just done quickly but I think it should work

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Dreagen
  • 1,733
  • 16
  • 21
  • Awesome! One more question please - How do I define MyFragment1() or MyFragment2() ? Thank you very kindly. – user3053246 Dec 17 '13 at 16:28
  • 3
    You have to create your own fragment, which is much like creating an Activity. Here is the android dev example which should be easy to follow http://developer.android.com/training/basics/fragments/creating.html – Dreagen Dec 17 '13 at 16:34
  • Yea. I have done all of this before .. The problem is, I dont know how to actually define the MyFragment1() - I got the "Cannot resolve the symbol.." error..¨ – user3053246 Dec 17 '13 at 16:40
  • You need a create a new class which extends Fragment and call it MyFragment1 (If you want to stick with my example). Once you have created the new class it will no longer give you the Cannot resolve error. If you're using android studio. Right click in your project > New > Android Component > New Blank Fragment and call it MyFragment1 - this will do most of the hard work for you – Dreagen Dec 17 '13 at 16:46
  • That seems right. Might need a bit more info on the crash. Your log cat should show you a stack trace which can be used to pin point the problem. You should be able to see the part of the stack trace that refers to your app. If not post it here – Dreagen Dec 17 '13 at 17:17
  • I guess I have done everything right but one problem appears - Variable "fragment" may not have been initialized (in .replace(R.id.container, FRAGMENT) The crash may have been caused by automatic fix that I used. – user3053246 Dec 17 '13 at 17:21
  • Sorry that's my fault! Thats what you get when you do things quickly. The fragment variable must be initialised with a fragment to begin with. So change `Fragment fragment;` to `Fragment fragment = new MyFragment1();` This will just set the default fragment to MyFragment1. Alternately you could use the default: section of the switch statement to set the fragment variable – Dreagen Dec 17 '13 at 17:24
  • I have found another problem and updated the question - can you please look at it? How do I add more fragments to the transaction? – user3053246 Dec 17 '13 at 17:39
  • 1
    Just create another fragment called MyFragment2 like you did with MyFragment1 and the code in my answer will work. (I will update it to fix the uninitialised variable). You don't need to create another fragment varibale as the first one we create gets changed depending on which navigation item you click on – Dreagen Dec 17 '13 at 17:43
  • 3
    What exactly does `R.id.container` refer to ? Is it a relativelayout or something? – nurettin Sep 24 '16 at 12:22
  • @nurettin `R.id.container` refers to whatever view has your fragments inside. – Dreagen Sep 26 '16 at 07:17
7

I solved this problem over inflater:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView;
        switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
            case 1:
                rootView = inflater.inflate(R.layout.fragment_obj_detail, container, false);
                break;
            case 2:
                rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
                break;
            case 3:
                rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
                break;
            case 4:
                rootView = inflater.inflate(R.layout.fragment_about, container, false);
                break;
            default:
                rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
        }
        return rootView;
    }
DenisGl
  • 87
  • 1
  • 2
  • 2
    As was pointed out below, doesn't this just inflate the layout, but nothing of the functionality? The code of fragment_obj_detail, fragment_obj_list, etc. isn't run using this method I believe. – saltandpepper Oct 01 '15 at 10:20
  • bad idea to write all in one file – Vlad Nov 23 '17 at 09:00
5

You need to create a switch block inside the onNavigationDrawerItemSelected() and use the code that's already there for every case but with corresponding Fragment instead of PlaceholderFragment. Now it contains a generic piece of code for adding a PlaceholderFragment to the layout, reuse it for your purposes.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • 4
    @user3053246, Sorry, I thought that given a position it's obvious on what you have to switch. And please don't rely on people writing code for you here. – Egor Dec 18 '13 at 08:17
2

The response of DenisGl, is the right way !!! Using the class member, created by default, you can switch between the various components of the Navigation Drawer !! You have to use the method onCreateView, which are within the class member PlaceholderFragment. This class will be automatically invoked in the method onNavigationDrawerItemSelected

Here is the code example: /This method can be left as it is! It automatically invoke the class PlaceholderFragment!/

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

This method instead, where you enter the Switch Case:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = null;
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
            case 1:
                rootView = inflater.inflate(R.layout.fragment_home, container, false);
                break;
            case 2:
                //rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
                break;
            case 3:
                //rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
                break;
            case 4:
                rootView = inflater.inflate(R.layout.fragment_info, container, false);
                break;
        }
        return rootView;
    }

Obviously, you have to call the layout for each fragment that interests us!

This works 100%, Test to verify!

Nemesis
  • 41
  • 5
  • 1
    This just inflates the Placeholder fragment with the layout, but the chosen fragment is still the Placeholder fragment. The fragment's layout will be shown, but its code won't be run,unless it's in the Placeholder fragment. Dreagens answer is the correct one. – Nublodeveloper Jun 27 '15 at 13:04
0

It does work in Eclipse IDE

   switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
        case 1:
            rootView = inflater.inflate(R.layout.fragment_home, container, false);
            break;
        case 2:
            //rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
            break;
        case 3:
            //rootView = inflater.inflate(R.layout.fragment_obj_list, container, false);
            break;
        case 4:
            rootView = inflater.inflate(R.layout.fragment_info, container, false);
            break;
    }

in function

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = null;
    rootView = inflater.inflate(R.layout.fragment_home, container, false);
    return rootView;
}
André Schild
  • 4,592
  • 5
  • 28
  • 42
0

In function:

   Bundle bundle = new Bundle();
   bundle.putInt("id", 10);//sending data to the second fragment                      
   NavHostFragment.findNavController(HomeFragment.this)//your fragment
   .navigate(R.id.action_nav_home_to_products_related_for_home_category,bundle);

In mobile_navigation.xml:

 <fragment
        android:id="@+id/nav_home"
        android:name="com.example.myapplication.ui.home.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" >
        <action
            android:id="@+id/action_nav_home_to_products_related_for_home_category"
            app:destination="@id/products_related_for_home_category"
            app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim"
            app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"
            >
            <argument
                android:name="myArg"
                app:argType="integer"
                android:defaultValue="1" />
        </action>
    </fragment>

In second fragment:

int id=getArguments().getInt("id");