Search code examples
xamarin.androidandroid-viewpagerandroid-tablayout

ViewPager not Loading Fragments when using TabLayout


I got a simple layout with TabLayout and PageViewer but can't get them to work together

   <com.google.android.material.tabs.TabLayout
    android:id="@+id/sliding_tabs_emoji"    
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:tabMode="scrollable"
        app:tabGravity="fill"    
        app:tabIndicatorColor="@color/gray"
        app:tabIndicatorHeight="1dp"
        android:paddingBottom="2dp"/>
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager_emoji"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/red"/>

In my Activity OnCreate initializing the following

//Fragment array
            var fragments = new AndroidX.Fragment.App.Fragment[]
            {
                Library.Fun.Emoji.Fragments.Recent.NewInstance(),
                Library.Fun.Emoji.Fragments.People.NewInstance(),               
            };
            //Tab title array
            var titles = Android.Runtime.CharSequence.ArrayFromStringArray(new[] {
                "Recent" ,
                "People"
            });

            var viewPager = FindViewById<ViewPager>(Resource.Id.viewpager_emoji);
            //viewpager holding fragment array and tab title text
            viewPager.Adapter = new EmojiTabsPagerAdapter(SupportFragmentManager, fragments, titles);            
            // Give the TabLayout the ViewPager
            TAB_Layout.SetupWithViewPager(viewPager);
            Toast.MakeText(this, "SET", ToastLength.Short);
            TAB_Layout.GetTabAt(0).SetIcon(Resource.Drawable.ic_camera);
            TAB_Layout.GetTabAt(1).SetIcon(Resource.Drawable.ic_camera);

Where the Adapter is simple as it could be as following

public class EmojiTabsPagerAdapter : FragmentPagerAdapter
    {
        private readonly AndroidX.Fragment.App.Fragment[] fragments;
        private readonly ICharSequence[] titles;

        public EmojiTabsPagerAdapter(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment[] fragments, ICharSequence[] titles) : base(fm)
        {
            this.fragments = fragments;
            this.titles = titles;
        }
        public override int Count
        {
            get
            {
                return fragments.Length;
            }
        }

        public override AndroidX.Fragment.App.Fragment GetItem(int position)
        {          
            return fragments[position];            
        }
        public override ICharSequence GetPageTitleFormatted(int position)
        {
            //return titles[position];
            return null;
        }
    }

Tabs are appearing but Fragments are not loading, The results are the following

enter image description here

Where it should load RECENT and PEOPLE fragments on each tab, my Fragment XML is the following

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="300dp"    
   android:background="@color/green">
  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="RECENTS"/>
</RelativeLayout>

And fragment's code is the following (for RECENT)

public class Recent : AndroidX.Fragment.App.Fragment
    {
        public static Recent NewInstance()
        {
            var frag = new Recent { Arguments = new Bundle() };
            return frag;
        }

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.fragment_emoji_recent, container, false);
            return view;
        }
    }

Any Idea what am I doing wrong?


Solution

  • I use two Fragments: TabFragment1, TabFragment2 to test. In your code, you did provide the code about SetupWithViewPager.

    The code below works well for me.

     void setupViewPager(Android.Support.V4.View.ViewPager viewPager)
        {
            var adapter = new Adapter(SupportFragmentManager);
            adapter.AddFragment(new TabFragment1(), "First Fragment");
            adapter.AddFragment(new TabFragment2(), "Second Fragment");
                       viewPager.Adapter = adapter;
            viewpager.Adapter.NotifyDataSetChanged();
            //viewpager.OffscreenPageLimit(4);
        }
    

    In MainActivity, you could set like below.

      var tabLayout = FindViewById<TabLayout>(Resource.Id.tabs);
            tabLayout.SetupWithViewPager(viewpager);
    

    enter image description here

    You could download the source file from the link: https://www.c-sharpcorner.com/article/xamarin-android-create-viewpager-tablayout-floatingactionbutton-supportacti/