Realizing a tab navigation inside an ActionBar navigation.
Asked Answered
A

0

3

Heyho. I'm trying to realize a tab navigation inside an ActionBar navigation (with fragments), but i can't get it work! Is this possible? It would be curious if not...

enter image description here .

This is what i already got:

MainActivity.java

...
import android.app.Fragment;
import android.app.FragmentTransaction;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        Fragment fragmentA = new FragmentA();
        ActionBar.Tab tabFragmentA = bar.newTab().setText("FragmentA");   
        tabFragmentA.setTabListener(new MyTabListener(fragmentA));
        bar.addTab(tabFragmentA);

        Fragment fragmentB = new FragmentB();
        ActionBar.Tab tabFragmentB = bar.newTab().setText("FragmentB");   
        tabFragmentB.setTabListener(new MyTabListener(fragmentB));
        bar.addTab(tabFragmentB);

        bar.setDisplayShowTitleEnabled(false); // remove top title bar
        bar.setDisplayShowHomeEnabled(false); 
    }

    public class MyTabListener implements TabListener {

        private Fragment fragment;

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

        @Override
        public void onTabSelected(Tab arg0, FragmentTransaction ft) {
            ft.replace(R.id.fragmentContainer, fragment);   
        }

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

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

I tried out the FragmentTabHost from the v4 support api, but when I am using this one I get a classcasterror in the MainActivity when I want to instantiate the Fragment. When I also change the Fragment import in the MainActivity to the support api, my tablistener isn't working anymore. So... what can I do? Any other suggestions?

FragmentA.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;

public class FragmentA extends Fragment {

    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_a, container, false);

        FragmentTabHost mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragmentAContainer);

        return view;
    }

}

Thank you for help!

Alain answered 16/5, 2013 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.