首页 > 解决方案 > 自动 Java 到 Kotlin 的转换:未解决的对“ARG_LAYOUT_RES_ID”的引用

问题描述

我在我的 Kotlin 应用程序中使用AppIntro,并且需要自定义其布局。本教程告诉我们使用此代码作为起点。因为那是用 Java 编写的,所以我将它转换为 Kotlin(虽然不是 100% 自动化,因为 Kotlin 不支持 'static' 关键字):

import android.support.v4.app.Fragment
import android.os.Bundle
import android.support.annotation.Nullable
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View


class IntroFragment: Fragment() {
    private val ARG_LAYOUT_RES_ID = "layoutResId"
    private var layoutResId: Int = 0

    companion object {
        fun newInstance(layoutResId: Int): IntroFragment{
            val args: Bundle = Bundle()
            args.putSerializable(ARG_LAYOUT_RES_ID, layoutResId)
            val fragment = IntroFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (arguments != null && arguments!!.containsKey(ARG_LAYOUT_RES_ID)) {
            layoutResId = arguments!!.getInt(ARG_LAYOUT_RES_ID)
        }
    }

    @Nullable
    override fun onCreateView(inflater: LayoutInflater, @Nullable container: ViewGroup?,
                              @Nullable savedInstanceState: Bundle?): View? {
        return inflater.inflate(layoutResId, container, false)
    }
}

在这部分:

 args.putSerializable(ARG_LAYOUT_RES_ID, layoutResId)

Android Studio 抱怨:

未解决的参考:ARG_LAYOUT_RES_ID

如何解决这个问题?

标签: androidkotlin

解决方案


这是因为它ARG_LAYOUT_RES_ID是一个实例变量,而您的newInstance方法是一个类(静态)方法。

如果您移动ARG_LAYOUT_RES_ID到伴随对象中,它将起作用。像这样:

import android.support.v4.app.Fragment
import android.os.Bundle
import android.support.annotation.Nullable
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View


class IntroFragment: Fragment() {
    private var layoutResId: Int = 0

    companion object {
        private const val ARG_LAYOUT_RES_ID = "layoutResId"

        fun newInstance(layoutResId: Int): IntroFragment {
            val args: Bundle = Bundle()
            args.putSerializable(ARG_LAYOUT_RES_ID, layoutResId)
            val fragment = IntroFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (arguments != null && arguments!!.containsKey(ARG_LAYOUT_RES_ID)) {
            layoutResId = arguments!!.getInt(ARG_LAYOUT_RES_ID)
        }
    }

    @Nullable
    override fun onCreateView(inflater: LayoutInflater,
                              @Nullable container: ViewGroup?,
                              @Nullable savedInstanceState: Bundle?): View? {

        return inflater.inflate(layoutResId, container, false)
    }
}

你也可以像我上面展示ARG_LAYOUT_RES_ID的那样。const


推荐阅读