Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/178.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 对象在Kotlin中处于未初始化状态,尽管进行了初始化_Android_Kotlin - Fatal编程技术网

Android 对象在Kotlin中处于未初始化状态,尽管进行了初始化

Android 对象在Kotlin中处于未初始化状态,尽管进行了初始化,android,kotlin,Android,Kotlin,我正在初始化我的MainActivity.kt的onCrete()方法中的RecyclerView对象,但不知何故它没有通过。我正在使用apply函数初始化我的RecyclerView对象并附加其必要的属性: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)

我正在初始化我的
MainActivity.kt
onCrete()
方法中的
RecyclerView
对象,但不知何故它没有通过。我正在使用
apply
函数初始化我的
RecyclerView
对象并附加其必要的属性:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ...

        adapter = EntryAdapter()
        layoutManager = LinearLayoutManager(this)

        recyclerView.apply{
            findViewById<RecyclerView>(R.id.userpass_recyclerview)
            layoutManager = layoutManager
            adapter = adapter
        }

        ...
    }

您没有在此处初始化
recyclerView
。您正在对尚未初始化的
lateinit
对象使用
apply
扩展

试试这个

recyclerView = findViewById<RecyclerView>(R.id.userpass_recyclerview)
recyclerView.apply {...}
recyclerView=findviewbyd(R.id.userpass\u recyclerView)
recyclerView.apply{…}
只需确保,您不会过早地执行
findviewbyd

class NestedRecyclerActivity : AppCompatActivity() {

private var recyclerOuter: RecyclerView? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_nested_recycler)

    recyclerOuter = findViewById(R.id.recyclerView)

    recyclerOuter!!.layoutManager = LinearLayoutManager(
        this, LinearLayoutManager.VERTICAL, false
    )
    val adapter = OuterAdapter(this)
    recyclerOuter!!.adapter = adapter
}

}

调用
apply
(与任何其他方法一样)方法需要已初始化的对象。但您正试图在
apply
的lambda中初始化它

因此,您需要首先调用
findviewbyd

recyclerView = findViewById<RecyclerView>(R.id.userpass_recyclerview)
recyclerView.apply {...}
recyclerView=findviewbyd(R.id.userpass\u recyclerView)
recyclerView.apply{…}
或者,要获得更少的代码:

recyclerView = findViewById<RecyclerView>(R.id.userpass_recyclerview).apply {
    ...
}
recyclerView=findviewbyd(R.id.userpass\u recyclerView)。应用{
...
}

不要忘记,只有在
setContentView

访问属性初始化它之后,才应该为任何视图调用
findViewById
?我看不到行号,但看起来像是发生了什么。永远不要进入
apply
方法。或get
NullPointerException
-取决于代码。
recyclerView = findViewById<RecyclerView>(R.id.userpass_recyclerview).apply {
    ...
}