android - 自动 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
如何解决这个问题?
解决方案
这是因为它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
推荐阅读
- java - 受密码保护的 zip 文件问题
- php - 仅显示特定类别的 WooCommerce 产品页面
- haskell - 通过指针将haskell GC分配的数据传递给C
- javascript - Typescript 在 node_modules 文件夹的定义文件中找不到类型
- android - Is it possible to save void in SharedPreferences
- python - pyInstaller 在捆绑包含 SWIG 模块的包时遇到问题
- python - 在 Keras 中使用大于 2 Gb 的数据集
- c# - EF Core 将 sql server DATEPART 实现为 DbFunction 静态方法
- mongoose - Artist.findOne 不是函数
- python - 协方差和相关系数