我要创建的ViewPager不是具有不同的片段,而是具有不同的布局。 所以我有带有main_activity布局的Activity。 main_activity中有一个容器,我想在其中更改布局。 我创建了CustomPagerAdapter,但是屏幕始终是白色的。
适配器代码:
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
}
}
在活动中初始化适配器:
layoutAdapter = LayoutPagerAdapter(layoutInflater)
container.adapter = layoutAdapter
活动布局:
<?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>
答案 0 :(得分:1)
尝试一下:
override fun instantiateItem(viewGroup: ViewGroup, position: Int): Any =
LayoutInflater.from(viewGroup.context).inflate(layouts[position], viewGroup, false).also {
viewGroup.add(it)
}