I'm going along, step by step to try and create a simple tab layout in Kotlin/Android. I've been pretty frustrated by a lot of the tutorials I've found as they either 1) work but are very over engineered making it difficult to see what's happening or 2) Don't seem to work.
This is one of case 2) that is very close to working, but there is something wrong. I've identified the problem, but I'm not sure how to solve it.
I have everything exactly as in the tutorial, and the only error that I am getting is in this part:
package com.ebookfrenzy.tablayoutdemo
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
class TabPagerAdapter(fm: FragmentManager, private var tabCount: Int) :
FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment? {
when (position) {
0 -> return Tab1Fragment()
1 -> return Tab2Fragment()
2 -> return Tab3Fragment()
3 -> return Tab4Fragment()
else -> return null
}
}
override fun getCount(): Int {
return tabCount
}
}
I am getting that Tab1Fragment(), Tab2...
all are not of type Fragment
which is the return type of fun getItem
. This is confusing, as they are classes that are declared like so:
class Tab1Fragment : Fragment()
That looks like it should be ok to me.
Here's a picture of what I'm seeing in case somebody doesn't believe me.
Can someone advise as to what's going on?
There are two probable errors in your code
Your fragment extends
android.support.v4.app.Fragment
and thegetItem()
method in your adapter returns anandroid.app.Fragment
or vice versa.In any case, ensure that both your fragment and the adapter methods return the same type preferably
android.support.v4.app.Fragment
and you're good to go.You should use
import android.support.v4.app.Fragment
Instead of
import android.app.Fragment