Android - ViewPager2, TabLayout, and Fragment

1. Prerequisites: Before using ViewPager2 and TabLayout, append
implementation 'com.google.android.material:material:$material_version'
to the build.gradle file.

2. Usage: a. Use ViewPager2 and TabLayout in the activity_main layout.

b. Create Fragment classes and their layout files. Warning: All subclasses of Fragment must include a public no-argument constructor.
class FragmentA: Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_a, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Change UI and use listeners here. } }

c. Connect Fragment to TabLayout in MainActivity.
viewPager.adapter = object : FragmentStateAdapter(this) { override fun getItemCount(): Int { return 2 } override fun createFragment(position: Int): Fragment { return when(position) { 0 -> FragmentA() else -> FragmentB() } } } TabLayoutMediator(tabLayout, viewPager) { tab, position -> tab.text = when(position) { 0 -> "FragmentA" else -> "FragmentB" } }.attach()

d. To prevent Fragment from refreshing, use
viewPager.offscreenPageLimit = 1

According to Android documentation,
If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth. You should keep this limit low, especially if your pages have complex layouts.


Comments

Popular posts from this blog

Manual - Modbus TCP Client

Manual - TCP / UDP Client

Manual - MQTT Client