android tab layout inside fragment not fragmentact

2019-06-10 05:44发布

问题:

I'm currently creating an application that uses navigation drawer and fragments . In one fragment I want to create a tab layout which should be made in a fragment activity . My question is whether there are alternative ways that can be used to implement the tab layout inside fragment ?. Thank you in advance

回答1:

Take a look at following code :

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class TabFragment extends Fragment {
FragmentTabHost mTabHost;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

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

    mTabHost = new FragmentTabHost(getActivity());
    mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.content);
    getActivity().getActionBar().setTitle("TabFragment");

    mTabHost.addTab(
                mTabHost.newTabSpec("First").setIndicator(
                        "First"), FirstFragment.class, null);

    mTabHost.addTab(mTabHost.newTabSpec("Second").setIndicator("Second"),
                SecondFragment.class, null);
    return mTabHost;

}

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
    mTabHost = null;
 }
}

Here R.id.content is FrameLayout where you showing fragments.(Like a layout named content_frame having only FrameLayout with id content.)



回答2:

You should be able to create a view with tab layout like in a normal activity. Then create your class for the tab layout and extend FragmentActivity and implement TabListener. In this fragment you just inflate the tabview into your fragmentcontainer like you do with all fragments and you should be able to do everything you're used to do with a TabLayout.

This links would probably be useful for you : Android Tab Layout inside Fragment