Hello Everyone, Today we are going to see tab layout with viewPager using 3 fragment.
Step 1 : Create Fragment.
New -> Fragment -> Fragment(Blank)
And Create 3 Fragment Name as Home, chat, Setting.
Step 2 : Setup ViewPager and TabLayout.
Open activity_main.xml file and Paste the Below code.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/purple_500"
app:tabSelectedTextColor="@color/purple_700"
app:tabTextAppearance="@style/TabLayoutTextStyle"
app:tabTextColor="@color/black"/>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/viewPager"
android:background="@color/white"
android:layout_weight="1"/>
</LinearLayout>
Step 3 : Create Fragment Adapter.
Right Click on Package Name -> New -> Kotlin File/Class.
Create Fragment Adapter Class and Paste the Below code.
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
class FragmentAdapter(fm : FragmentManager) : FragmentStatePagerAdapter(fm,
BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
var fragmentList : ArrayList<Fragment> = ArrayList()
var fragmenttitle : ArrayList<String> = ArrayList()
override fun getCount(): Int {
return fragmentList.size
}
override fun getItem(position: Int): Fragment {
return fragmentList[position]
}
override fun getPageTitle(position: Int): CharSequence? {
return fragmenttitle[position]
}
fun addFragment(fragment: Fragment,title : String){
fragmentList.add(fragment)
fragmenttitle.add(title)
}
}
Step 4 : Create Object of Viewpager and Setup Tabs.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var viewPager = findViewById(R.id.viewPager) as ViewPager
var tablayout = findViewById(R.id.tablayout) as TabLayout
val fragmentAdapter = FragmentAdapter(supportFragmentManager)
fragmentAdapter.addFragment(HomeFragment(),"Home")
fragmentAdapter.addFragment(ChatFragment(),"Chat")
fragmentAdapter.addFragment(SettingsFragment(),"Settings")
viewPager.adapter = fragmentAdapter
tablayout.setupWithViewPager(viewPager)
}
}
Thank You !!
Subscribe to Our Channel.
0 Comments