简体   繁体   English

如何在Kotlin中创建具有不同布局的ViewPager?

[英]How to create ViewPager with different layouts in Kotlin?

I want to create ViewPager not with different fragments but with different layouts. 我要创建的ViewPager不是具有不同的片段,而是具有不同的布局。 So I have Activity with main_activity layout. 所以我有带有main_activity布局的Activity。 There is container in main_activity, where I want to change layouts. main_activity中有一个容器,我想在其中更改布局。 I created CustomPagerAdapter, but screens is always white. 我创建了CustomPagerAdapter,但是屏幕始终是白色的。

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>

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM