Unable to add Tabs inside Fragment of Navigation Drawer Android

Vishnu picture Vishnu · Nov 8, 2013 · Viewed 7.5k times · Source

1) I have followed the Navigation Drawer example in Android Developer Docs here developer.android.com/training/implementing-navigation/nav-drawer.html
and created my whole application. In the given example, they have used Fragments for each item selected in the Drawer called fragments with following code

Bundle args = new Bundle();
args.putInt("Title_Number", position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

2) Now I want a Tab behavior inside a Fragment i.e., when I select a particular item in the Nav-Drawer, the Fragment loaded should display a Tab bar on the top something like this. http://flic.kr/p/hn4G3i

3) I have followed the tutorial and example given here
developer.android.com/training/implementing-navigation/lateral.html,
but the example given here is using FragmentActivity which is not compatible with Fragments (as per my knowledge).

Could someone help me achieving this behaviour in my app. Thanks in advance.

Answer

Vishnu picture Vishnu · Nov 12, 2013
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import cgg.gov.in.apps.eoffice.source.R;

public class TestTabsinsideFragment extends Fragment
{
    View rootView;

public TestTabsinsideFragment () 
{
    // Empty constructor required for fragment subclasses
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState)
{   

getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Apply the layout for the fragment
rootView = inflater.inflate(R.layout.approve_leaves, container, false);


getActivity().setTitle("New tabbed layout inside Fragment :-) ");


ActionBar.TabListener tabListener = new ActionBar.TabListener() {
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        // show the given tab
    }

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        // hide the given tab
    }

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        // probably ignore this event
    }
};

// Add 3 tabs, specifying the tab's text and TabListener
for (int i1 = 0; i1 < 3; i1++) {
    getActivity().getActionBar().addTab(
            getActivity().getActionBar().newTab()
            .setText("Tab " + (i1 + 1))
            .setTabListener(tabListener));
}


return rootView;
}

I have fixed the problem myself. :D