Search code examples
user-interfaceandroid-viewpagerandroid-tablayout

Why tabs are not visible in the fragment when using Tablayout with viewpager?


So, I am working on my android project and I am developing UI for my community page (which is a fragment). I am using Tablayout and viewpager. I have done everything and set up the adapter as well but when I run the app the tabs are not visible.

fragment_bite_back_community.xml:

<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="match_parent"
    tools:context=".fragment.BiteBackCommunityFragment">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/communityTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabGravity="fill"
        app:tabMode="fixed">

        <!-- Add TabItems for each tab -->
        <com.google.android.material.tabs.TabItem
            android:id="@+id/tabFeed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/feed" />

        <com.google.android.material.tabs.TabItem
            android:id="@+id/tabExplore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/explore" />

        <com.google.android.material.tabs.TabItem
            android:id="@+id/tabCreatePost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/create_post" />
    </com.google.android.material.tabs.TabLayout>

    <!-- ViewPager for managing fragments in tabs -->
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/communityTabLayout" />

</RelativeLayout>

My CommunityPagerAdapter:

// CommunityPagerAdapter

package com.saurtech.biteback.adapter

import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.PagerAdapter
import com.saurtech.biteback.fragment.CommunityCreatePostFragment
import com.saurtech.biteback.fragment.CommunityExploreFragment
import com.saurtech.biteback.fragment.CommunityFeedFragment

class CommunityPagerAdapter(private val fm: FragmentManager) : PagerAdapter() {

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        // Return the fragment based on the position
        val fragment: Fragment = when (position) {
            0 -> CommunityFeedFragment()
            1 -> CommunityExploreFragment()
            2 -> CommunityCreatePostFragment()
            else -> throw IllegalArgumentException("Invalid tab position")
        }

        val transaction = fm.beginTransaction()
        transaction.add(container.id, fragment)
        transaction.commitAllowingStateLoss()

        return fragment
    }

    override fun getCount(): Int {
        // Return the total number of tabs
        return 3
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun getPageTitle(position: Int): CharSequence? {
        // Return tab title based on position
        return when (position) {
            0 -> "Community Feed"
            1 -> "Explore"
            2 -> "Create Post"
            else -> null
        }
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        val transaction = fm.beginTransaction()
        transaction.remove(`object` as Fragment)
        transaction.commitAllowingStateLoss()
    }
}

My BiteBackCommunityFragment.kt:

package com.saurtech.biteback.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.saurtech.biteback.R
import com.saurtech.biteback.adapter.CommunityPagerAdapter

class BiteBackCommunityFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_bite_back_community, container, false)

        // Setup ViewPager
        val viewPager: ViewPager = view.findViewById(R.id.viewPager)

        val pagerAdapter: PagerAdapter = CommunityPagerAdapter(childFragmentManager)
        viewPager.adapter = pagerAdapter

        // Setup TabLayout
        val tabLayout: TabLayout = view.findViewById(R.id.communityTabLayout)
        tabLayout.setupWithViewPager(viewPager)

        return view
    }
}

There are no errors and the app is running fine but can't see the tabs.

This is the screen I am getting. This is the page I am getting

This is the desired Output. This is the desired Output


Solution

  • So, I tried every possible way to make this work and finally got the view correct.

    I just made a few adjustments like placing the TabLayout to the top and used ViewPager2 this time below the TabLayout.

    fragment_bite_back_community.xml:

    <androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
        tools:context=".fragment.BiteBackCommunityFragment">
        
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/communityTabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:tabGravity="fill"
            app:tabMode="fixed">
            
            <com.google.android.material.tabs.TabItem
                android:id="@+id/tabFeed"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/feed" />
    
            <com.google.android.material.tabs.TabItem
                android:id="@+id/tabExplore"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/explore" />
    
            <com.google.android.material.tabs.TabItem
                android:id="@+id/tabCreatePost"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/create_post" />
        </com.google.android.material.tabs.TabLayout>
        
        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/communityTabLayout" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Changed a few things in CommunityPagerAdapter.kt and now it looks like this:

    // CommunityPagerAdapter
    package com.saurtech.biteback.adapter
    
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.FragmentManager
    import androidx.lifecycle.Lifecycle
    import androidx.viewpager2.adapter.FragmentStateAdapter
    import com.saurtech.biteback.fragment.CommunityCreatePostFragment
    import com.saurtech.biteback.fragment.CommunityExploreFragment
    import com.saurtech.biteback.fragment.CommunityFeedFragment
    
    class CommunityPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
        FragmentStateAdapter(fragmentManager, lifecycle) {
    
        override fun getItemCount(): Int {
            return 3 // Return the total number of tabs
        }
    
        override fun createFragment(position: Int): Fragment {
            // Return the fragment based on the position
            return when (position) {
                0 -> CommunityFeedFragment()
                1 -> CommunityExploreFragment()
                2 -> CommunityCreatePostFragment()
                else -> throw IllegalArgumentException("Invalid tab position")
            }
        }
    }
    

    And last BiteBackCommunityFragment.kt file:

    package com.saurtech.biteback.fragment
    
    // BiteBackCommunityFragment.kt
    import android.os.Bundle
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import androidx.fragment.app.Fragment
    import androidx.viewpager2.widget.ViewPager2
    import com.google.android.material.tabs.TabLayout
    import com.google.android.material.tabs.TabLayoutMediator
    import com.saurtech.biteback.R
    import com.saurtech.biteback.adapter.CommunityPagerAdapter
    
    class BiteBackCommunityFragment : Fragment() {
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val view = inflater.inflate(R.layout.fragment_bite_back_community, container, false)
    
            // Setup ViewPager
            val viewPager: ViewPager2 = view.findViewById(R.id.viewPager)
            val pagerAdapter = CommunityPagerAdapter(childFragmentManager, lifecycle)
            viewPager.adapter = pagerAdapter
    
            // Setup TabLayout using TabLayoutMediator
            val tabLayout: TabLayout = view.findViewById(R.id.communityTabLayout)
            TabLayoutMediator(tabLayout, viewPager) { tab, position ->
                when (position) {
                    0 -> tab.text = "Feed"
                    1 -> tab.text = "Explore"
                    2 -> tab.text = "Create Post"
                }
            }.attach()
    
            return view
        }
    }
    

    Previously I was trying to make the TabLayout at the bottom which was not working so this time placed it at the top and now its working perfectly fine.