0

Trying to create Facebook / Gmail style Sliding Navigation Drawer. All I want is to create separate Fragments in XML, and show them when user clicks one of the list items from Drawer Menu. Each Fragment hooked up to one item in the list.

NavigationDrawer is great example app to start with, but it only demos loading fragment dynamically. I want even simpler, just loading those statically. How should (Code snippet please) I be instantiating Fragments within my activity on List menu item click? How would MainActivity XML look like ?

Fragment 2

Fragment 3

Community
  • 1
  • 1
Khulja Sim Sim
  • 3,469
  • 1
  • 29
  • 28

1 Answers1

1

Please read the docs http://developer.android.com/guide/components/fragments.html

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
         android:id="+@id/fragment_container"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
    />
</LinearLayout>

Java

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Patrick
  • 33,984
  • 10
  • 106
  • 126
  • When I create ExampleFragment from New > Android Object > Blank Fragment, I get a subclass of Fragment. For some reason, I get compilation error @ fragmentTrasaction.add( ..) suggesting me, change fragment type from ExampleFragment to Fragment. I'm not sure if you compiled your code, it has some bugs, but that's no biggie. – Khulja Sim Sim May 02 '14 at 20:46
  • Plus, fragmentTransaction.add() is only for adding fragments dynamically, not for static XML layouts. – Khulja Sim Sim May 02 '14 at 20:49
  • 1
    @compiler: you probably mixing Fragment with v4.support.Fragment. There is no "static" loading. Either you define the fragment in the xml (see the link) or you dynamically add them upon pressing the menu button. This is THE classic use case for dynamic adding of fragmentr – Patrick May 02 '14 at 21:11
  • your solution isn't bad but not certainly what I was looking for. I ended up using startIntent() on navigation drawer item selection callback. That way, I could open up new activity / fragment within those activities. – Khulja Sim Sim May 15 '14 at 02:04