not showing content of tablayout in fragment

时间:2018-06-18 11:40:57

标签: android fragment

I using tablayout in fragment but when transation as from Fragment 1 to Fragment2 and back to Fragment1,content of tablayout is not show...

Like the gif below:

Gif

fragment tab:

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_chat, container, false);


    tabLayout = (TabLayout) view.findViewById(R.id.tablayout_chat);
    viewPager = (ViewPager) view.findViewById(R.id.viewpager_chat);


    Activity_Main.img_home.setImageDrawable(getResources().getDrawable(R.drawable.home));
    Activity_Main.img_chat.setImageDrawable(getResources().getDrawable(R.drawable.s_chat));
    Activity_Main.img_setting.setImageDrawable(getResources().getDrawable(R.drawable.setting));


    AdapterTab_Chat adapterTab_chat = new AdapterTab_Chat(mcontex.getSupportFragmentManager());
    viewPager.setAdapter(adapterTab_chat);

    viewPager.setCurrentItem(1);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    return view;
}


@Override
public void onAttach(Context context) {
    mcontex = (FragmentActivity) context;
    super.onAttach(context);
}

how fix it ???

2 个答案:

答案 0 :(得分:0)

再次创建FragmentManager

......
     FragmentManager fragmnetManager=mcontex.getSupportFragmentManager();
    AdapterTab_Chat adapterTab_chat = new   AdapterTab_Chat(fragmnetManager);
viewPager.setAdapter(adapterTab_chat);

viewPager.setCurrentItem(1);

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        fragmnetManager=mcontex.getSupportFragmentManager();
        viewPager.setCurrentItem(tab.getPosition());
    }....

还为位置=> CurrentItem(1)

中的片段创建新的fragmentManager

答案 1 :(得分:0)

试试这个

使用getChildFragmentManager()代替getSupportFragmentManager()

getChildFragmentManager()到其构造函数

AdapterTab_Chat adapterTab_chat = new AdapterTab_Chat(getChildFragmentManager());
    viewPager.setAdapter(adapterTab_chat);

这会将这些片段添加到堆栈中,并在使用view pager

加载片段时再次加载