Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager inside Fragment

I am trying to add a viewpager to a fragment using the new android support design library. I have my xml code for the layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

And the corresponding java class is as follows:

public class Tracks extends Fragment {

    ViewPager viewPager;
    TabLayout tabLayout;

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

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

        AppCompatActivity activity = (AppCompatActivity) getActivity();
        assert activity.getSupportActionBar() != null;
        activity.getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_theme)));

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

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

            }

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

            }
        });
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        viewPagerAdapter.addFragment(new TopTracks(), "Top Tracks");
        viewPagerAdapter.addFragment(new WorldCharts(), "World Charts");
        viewPagerAdapter.addFragment(new NewMusic(), "New Music");
        viewPagerAdapter.addFragment(new AfricaHot(), "Africa Hot");
        viewPagerAdapter.addFragment(new Playlists(), "Playlists");
        viewPagerAdapter.addFragment(new Recommended(), "Recommended");
        viewPager.setAdapter(viewPagerAdapter);
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter {

        List<Fragment> fragmentList = new ArrayList<>();
        List<String> fragmentTitles = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitles.get(position);
        }

        public void addFragment(Fragment fragment, String name) {
            fragmentList.add(fragment);
            fragmentTitles.add(name);
        }
    }
}

The viewpager works correctly save for the fact that my tabs wont show. All i get is the following screen:

The tablayout is present but tabs are absent

I have gone through the code many times but i still cant seem to get what is wrong with my code

like image 447
Alex Kombo Avatar asked Sep 26 '22 22:09

Alex Kombo


1 Answers

That's a common bug with design support library related to ViewCompat.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setupViewPager(viewPager);
    // after you set the adapter you have to check if view is laid out, i did a custom method for it
    if (ViewCompat.isLaidOut(tabLayout)) {
        setViewPagerListener();
    } else {
        tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
           @Override
           public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                setViewPagerListener();
                tabLayout.removeOnLayoutChangeListener(this);
           }
       });
    }
}

private void setViewPagerListener() {
    tabLayout.setupWithViewPager(viewPager);
    // use class TabLayout.ViewPagerOnTabSelectedListener
    // note that it's a class not an interface as OnTabSelectedListener, so you can't implement it in your activity/fragment
    // methods are optional, so if you don't use them, you can not override them (e.g. onTabUnselected)
    tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            super.onTabReselected(tab);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            super.onTabSelected(tab);
        }
    });
}

Also, holding onto a list of Fragment instances in a ViewPagerAdapter (especially FragmentPagerAdapter) will most likely cause crashes after process death in production, so your adapter should look like this:

public class ViewPagerAdapter extends FragmentPagerAdapter {
    public ViewPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0) return new TopTracks();
        if(position == 1) return new WorldCharts();
        if(position == 2) return new NewMusic();
        if(position == 3) return new AfricaHot();
        if(position == 4) return new Playlists();
        if(position == 5) return new Recommended();
        throw new IllegalStateException("Unexpected position " + position);
    }

    @Override
    public int getCount() {
        return 6;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if(position == 0) return "Top Tracks";
        if(position == 1) return "World Charts";
        if(position == 2) return "New Music";
        if(position == 3) return "Africa Hot";
        if(position == 4) return "Playlists";
        if(position == 5) return "Recommended";
        throw new IllegalStateException("Unexpected position " + position);
    }
}
like image 194
Giorgio Antonioli Avatar answered Sep 30 '22 06:09

Giorgio Antonioli