尽管初始化,对象在Kotlin中仍未初始化

时间:2019-06-06 06:05:21

标签: android kotlin

我正在用RecyclerView的{​​{1}}方法初始化MainActivity.kt对象,但是不成功。我正在使用onCrete()函数初始化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
        }

        ...
    }

3 个答案:

答案 0 :(得分:2)

调用<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>(和其他任何方法一样)需要已初始化的对象。但是您正在尝试在apply的lambda中对其进行初始化。

因此,您需要先致电apply

findViewById

或者,获得更少的代码:

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

请不要忘记,只有在recyclerView = findViewById<RecyclerView>(R.id.userpass_recyclerview).apply { ... } 之后,才应调用findViewById进行任何视图。

答案 1 :(得分:0)

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

尝试一下

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

请确保您没有太早完成findViewById

答案 2 :(得分:0)

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
}

}