androidkotlinandroid-viewpagerandroid-pageradapter

How to create ViewPager with different layouts in Kotlin?


I want to create ViewPager not with different fragments but with different layouts. So I have Activity with main_activity layout. There is container in main_activity, where I want to change layouts. I created CustomPagerAdapter, but screens is always white.

Adapter code:

class LayoutPagerAdapter(val layoutInflater: LayoutInflater): PagerAdapter(){

    val layouts: Array<Int> = arrayOf(R.layout.layout1, R.layout.layout2,
            R.layout.layout3, R.layout.layout4,
            R.layout.layout5, R.layout.layout6)

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

    override fun getCount(): Int {
        return layouts.size
    }

    override fun destroyItem(parent: ViewGroup, position: Int, `object`: Any) {
        parent.removeView(`object` as View)
    }

    override fun instantiateItem(viewGroup: ViewGroup, position: Int): Any {
        var view = layoutInflater.inflate(layouts[position], viewGroup, true)

        return view
    }
}

initialize Adapter in Activity:

   layoutAdapter = LayoutPagerAdapter(layoutInflater)
        container.adapter = layoutAdapter

Activity layout:

<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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:id="@+id/main_content"
    android:layout_width="match_parent"

    android:layout_height="match_parent"
    >


    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="?attr/actionBarSize"

        />

</android.support.design.widget.CoordinatorLayout>

Solution

  • Try this:

    override fun instantiateItem(viewGroup: ViewGroup, position: Int): Any =
        LayoutInflater.from(viewGroup.context).inflate(layouts[position], viewGroup, false).also {
            viewGroup.addView(it)
        }