Android Kotlin中的片段类型不匹配 [英] Fragment Type Mismatch in Android Kotlin

查看:153
本文介绍了Android Kotlin中的片段类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在逐步尝试在Kotlin/Android中创建简单的标签布局.我对许多教程感到非常沮丧,因为它们要么是1)工作正常,但由于设计过度,很难看到正在发生的事情,或者2)似乎无效.

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.

这是情况2)之一,非常接近工作,但有问题.我已经确定了问题,但不确定如何解决.

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_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
    }
}

我发现Tab1Fragment(), Tab2...的类型都不是Fragment的类型,而这是fun getItem的返回类型.这很令人困惑,因为它们是这样声明的类:

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()

我觉得应该没问题.

这是我所看到的图片,以防有人不相信我.

Here's a picture of what I'm seeing in case somebody doesn't believe me.

https://imgur.com/a/XvZaP

有人可以提供建议吗?

推荐答案

您的代码中可能存在两个错误

There are two probable errors in your code

您的片段扩展了android.support.v4.app.Fragment,适配器中的getItem()方法将返回android.app.Fragment,反之亦然.

Your fragment extends android.support.v4.app.Fragment and the getItem() method in your adapter returns an android.app.Fragment or vice versa.

无论如何,请确保片段和适配器方法最好返回相同的类型,最好是android.support.v4.app.Fragment,并且一切顺利.

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.

这篇关于Android Kotlin中的片段类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆