uLYsseus
uLYsseus

Reputation: 1006

Adding/Replacing Fragments within Fragments under ActionBar Tabs

Im not sure if I am missing any basics here. I have an activity hosting Action Bar Tabs: So here is the structure MainActivity -> Has two ActionBar Tabs F1 and F2 || Frag.java is the container fragment which hosts the xml defining a FrameLayout to be replaced|| F1 is Frag1.java where Frag1.java is obviously our good old fragment|| F2 is Frag2.java where Frag2.java is another fragment In my MainActivity I create two tabs, *NOTE:*both with same fragments which is Frag.java, then within the Frag.java onCreateView I try adding the fragment. This doesn not happen whats the problem.

(Ideally I want the fragments under a tab to be replaced by another fragement on a button click event)

This is my main activity

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {
    @Override
    protected void onCreate(Bundle arg0) {

        super.onCreate(arg0);

        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


        ActionBar.Tab FragTab1 = actionBar.newTab().setText("F1");
        ActionBar.Tab FragTab2 = actionBar.newTab().setText("F2");

        Fragment fragment1 = new Frag();
        Fragment fragment2 = new Frag2();

        FragTab1.setTabListener(new MyTabListener(fragment1));
        FragTab2.setTabListener(new MyTabListener(fragment2));

        actionBar.addTab(FragTab1,0,true);
        actionBar.addTab(FragTab2,1,false);

    }


class MyTabListener implements ActionBar.TabListener
        {
            Fragment fragment;

            public MyTabListener(Fragment fragment)
            {
                this.fragment=fragment;
            }

            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {}

            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {  }

            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft) {}}}

And coming to my simple fragments I have three setup Frag, Frag1, frag2

below is frag.java

public class Frag extends SherlockFragment {

    public Frag() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.parent, container,false);

      FragmentManager fm = getFragmentManager();
      FragmentTransaction ft= fm.beginTransaction();


        Frag1 f1 = new Frag1();
        ft.add(R.id.contentFragment, f1);
        ft.commit();

        return  v;
    }


}

below is my parent.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/contentFragment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" >
        </FrameLayout>

    </LinearLayout>

below is frag2.java

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.frag1, container, false);
        Button btn = (Button)v.findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Frag2 fragment = new Frag2();

                FragmentManager fm = getFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.replace(R.id.contentFragment, fragment);
                transaction.commit();

            }
        });
        return v;
    }

and In the above fragment you see that the button click is supposed to replace the fragment, but I am not even able to get this fragment in place.

Ive been juggling with this since three days. I would really appreciate any help or suggestions here or it would be awesome if anyone could direct me where I am going wrong !

Upvotes: 1

Views: 2360

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

Change your MainActivity to

public class MainActivity extends SherlockFragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab FragTab1 = actionBar.newTab().setText("F1");
        ActionBar.Tab FragTab2 = actionBar.newTab().setText("F2");

        FragTab1.setTabListener(new TabListener<MyFragmentA>(this, "F1",
                Frag.class));
        FragTab1.setTabListener(new TabListener<MyFragmentB>(this, "F2",
                Frag2.class));

        actionBar.addTab(FragTab1, 0, true);
        actionBar.addTab(FragTab2, 1, false);

        if (savedInstanceState != null) {
            int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
            getSupportActionBar().setSelectedNavigationItem(savedIndex);
        }

    }

    public static class TabListener<T extends Fragment> implements
            ActionBar.TabListener {

        Fragment fragment;

        private final Activity myActivity;
        private final String myTag;
        private final Class<T> myClass;

        public TabListener(Activity activity, String tag, Class<T> cls) {
            myActivity = activity;
            myTag = tag;
            myClass = cls;
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {

            Fragment myFragment = myActivity.getFragmentManager()
                    .findFragmentByTag(myTag);

            // Check if the fragment is already initialized
            if (myFragment == null) {
                // If not, instantiate and add it to the activity
                myFragment = Fragment
                        .instantiate(myActivity, myClass.getName());
                ft.add(android.R.id.content, myFragment, myTag);
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(myFragment);
            }

        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {

            Fragment myFragment = myActivity.getFragmentManager()
                    .findFragmentByTag(myTag);

            if (myFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(myFragment);

            }

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub

        }

    }
}

When you click on the tabs the fragment gets attached and when you select another tab detach the current fragment and attach another fragment.

Not sure what you are trying to do in Frag and Frag2

 View v = inflater.inflate(R.layout.parent, container,false);

You are inflating parent.xml in Frag. I believe that is not what you want. Instead have xml layout for each fragment and inflate the layout for the same.

Upvotes: 1

Related Questions