SoFunction
Updated on 2025-04-12

Kotlin efficient implementation of Android ViewPager2 Top Navigation Dynamic Configuration and Performance Optimization Guide (Recommended)

  • Efficient implementation: Emphasize the performance optimization of the code.
  • Android ViewPager2: Clear the technology stack.
  • Top Navigation: Core functional points.
  • Dynamic Configuration and Performance Optimization Guide: Highlight the focus of dynamic configuration flexibility and performance optimization.

In Android development, useViewPager2Achieve efficient top navigation (usually combined withTabLayout) is a common requirement. The following is an optimized implementation solution to ensure that the code is efficient, concise and easy to maintain.

Optimization goals

  • Efficient loading: Take advantage of the FragmentStateAdapter feature to avoid unnecessary Fragment instantiation.
  • Dynamic configuration: Dynamically configure TabLayout and ViewPager2 through data-driven methods.
  • Concise code: Use Kotlin's features and extension functions to reduce redundant code.
  • Scalability: Easy to add or delete pages without modifying core logic.

Implementation steps

1. Add dependencies

Make sure to be inAdded inViewPager2andMaterial Designrely:

dependencies {
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
    implementation ':material:1.4.0'
}

2. Define page data

usesealed classordata classDefine page information, including title, icon and correspondingFragment

// 
sealed class Page(val title: String, val icon: Int) {
    object Home : Page("Home", .ic_home)
    object Dashboard : Page("Dashboard", .ic_dashboard)
    object Notifications : Page("Notifications", .ic_notifications)
    companion object {
        val pages = listOf(Home, Dashboard, Notifications)
    }
}

3. Create a Fragment

Create a corresponding page for each pageFragment

// 
class Fragment1 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.fragment_1, container, false)
    }
}
// 
class Fragment2 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.fragment_2, container, false)
    }
}
// 
class Fragment3 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.fragment_3, container, false)
    }
}

4. Create an adapter

useFragmentStateAdapterDynamic loadingFragment

class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
    override fun getItemCount(): Int = 
    override fun createFragment(position: Int): Fragment {
        return when ([position]) {
            is  -> Fragment1()
            is  -> Fragment2()
            is  -> Fragment3()
        }
    }
}

5. Set up ViewPager2 and TabLayout

existMainActivitySettings inViewPager2andTabLayoutlinkage.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_main)
        val viewPager = findViewById<ViewPager2>()
        val tabLayout = findViewById<TabLayout>()
        // Set up ViewPager2 adapter         = ViewPagerAdapter(this)
        // Link TabLayout with ViewPager2        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
             = [position].title
             = (this, [position].icon)
        }.attach()
    }
}

6. Layout Files

existactivity_main.xmldefines the layout, includingTabLayoutandViewPager2

<LinearLayout xmlns:andro
    xmlns:app="/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- Top Navigation -->
    <
        android:
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>
    <!-- ViewPager2 -->
    <androidx..ViewPager2
        android:
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
</LinearLayout>

7. Extended functions: Simplify TabLayout configuration

If frequent configuration is requiredTabLayout, it can be encapsulated as an extension function.

// 
fun (viewPager: ViewPager2, pages: List<Page>) {
    TabLayoutMediator(this, viewPager) { tab, position ->
         = pages[position].title
         = (context, pages[position].icon)
    }.attach()
}

existMainActivityUsed in:

(viewPager, )

Advantages after optimization

  • Efficient loadingFragmentStateAdaptermake sureFragmentEfficient management of instances.
  • Dynamic configuration:passDynamically configure the page to avoid hard-code.
  • Concise code: Extended functions and Kotlin features make the code more concise.
  • Scalability: Add a new page just inPageAdd a new object to the core logic without modifying it.

Example: Add a new page

If you need to add a new page, justPageAdd a new object to:

object Profile : Page("Profile", .ic_profile)

Then inViewPagerAdapterProcess new pages:

override fun createFragment(position: Int): Fragment {
    return when ([position]) {
        is  -&gt; Fragment1()
        is  -&gt; Fragment2()
        is  -&gt; Fragment3()
        is  -&gt; Fragment4() // Add a new page    }
}

The system will automatically synchronize other codes without modificationTabLayout

Summarize

Through the above optimization,ViewPager2Code for implementing top navigation becomes more efficient, concise and easy to maintain.sealed classThe use of extended functions makes the code more readable and extensible while avoiding hard-coded and duplicate logic. Run the optimized code and you will get an efficient top navigation implementation.

This is the article about the dynamic configuration and performance optimization guide (recommended) of Kotlin's efficient implementation of Android ViewPager2 top navigation. For more information about Kotlin Android ViewPager2 top navigation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!