Fragment Type Mismatch in Android Kotlin

2019-07-13 03:51发布

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.

http://www.techotopia.com/index.php/Kotlin_-_Creating_a_Tabbed_Interface_using_the_TabLayout_Component

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.

https://imgur.com/a/XvZaP

Can someone advise as to what's going on?

2条回答
forever°为你锁心
2楼-- · 2019-07-13 03:57

There are two probable errors in your code

Your fragment extends android.support.v4.app.Fragment and the getItem() method in your adapter returns an android.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.

查看更多
We Are One
3楼-- · 2019-07-13 04:13

You should use

import android.support.v4.app.Fragment

Instead of

import android.app.Fragment

查看更多
登录 后发表回答