Jomia
Jomia

Reputation: 3404

Dynamically change content of a drawer using fragments

I need to change the drawer content dynamically. I plan to do it with fragments. Means start new fragments to change the view of drawer. Actually my drawer itself a fragment. I have given code like this inside the first fragment:

@Override
public void onActivityCreated (Bundle savedInstanceState) 
{ 
    super.onActivityCreated(savedInstanceState);
    LinearLayout helpLL = (LinearLayout) getView().findViewById(R.id.helpLL);
    helpLL.setOnClickListener(new OnClickListener()
    {           
        @Override
        public void onClick(View v)
        {
                Fragment detail = new DetailFragment();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.left_drawer, detail).commit();                                 
        }
    });
}

I need to change the entire drawer view with this layout. left_drawer is the view in main.xml where my first fragment lies. But when I click, nothing is happening.

Please tell me what wrong I did with this code.

Thanks Jomia

Upvotes: 0

Views: 613

Answers (1)

Jomia
Jomia

Reputation: 3404

I finally found the solution. I did a mistake in my code.Actually I hard coded the fragment in xml for the first drawer. Fragments that are hard coded in XML, cannot be replaced. Thats why the second fragment is not created.

So I added the first fragment dynamically. Now it is working fine..

In main.xml

    <LinearLayout android:layout_width="240dp"
        android:layout_height="match_parent" 
        android:id="@+id/left_drawer"   
        android:layout_weight="1"
        android:layout_gravity="right"
        android:orientation="vertical">
   </LinearLayout>

In Activity

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        settingsFragment = new SettingsFragment();
        fragmentTransaction.add(R.id.left_drawer, settingsFragment, "settingsFragment");
        fragmentTransaction.commit();

In SettingsFragment.java

    @Override
    public void onActivityCreated (Bundle savedInstanceState) 
    {
        super.onActivityCreated(savedInstanceState);
        LinearLayout helpLL = (LinearLayout) getView().findViewById(R.id.helpLL);
        helpLL.setOnClickListener(new OnClickListener()
        {           
            @Override
            public void onClick(View v)
            {           
                Fragment detail = new DetailFragment();
                FragmentManager fragmentManager = getFragmentManager();            
                fragmentManager.beginTransaction().replace(R.id.left_drawer, detail,"Details").commit();
            }
        });
    }

Thats all...

Upvotes: 2

Related Questions