w_bianrytree
10/09/2019, 9:27 AMclass MyView:View{
private val myChildView:View = findViewById(R.id.my_view_id)
init{
View.inflate(R.layout.my_layout,this)
}
}
There is a chance that myChildView is null because inflation is executed after findViewById.Luca Nicoletti
10/09/2019, 9:28 AMw_bianrytree
10/09/2019, 9:29 AMdiesieben07
10/09/2019, 9:29 AMthis
escape in the init block. that is usually a bad idea.fun main() {
Foo()
}
fun getString() = "hello"
fun doWithString(s: String, foo: Foo) {
println(s)
println(foo.x)
}
class Foo {
val x: String = getString()
init {
doWithString(x, this)
}
}
Luca Nicoletti
10/09/2019, 9:32 AMdiesieben07
10/09/2019, 9:32 AMw_bianrytree
10/09/2019, 9:33 AMdiesieben07
10/09/2019, 9:34 AMfindViewById
runs after inflate
?Luca Nicoletti
10/09/2019, 9:34 AMdiesieben07
10/09/2019, 9:35 AMw_bianrytree
10/09/2019, 9:36 AMdiesieben07
10/09/2019, 9:39 AMw_bianrytree
10/09/2019, 9:40 AMdiesieben07
10/09/2019, 9:43 AMAlexander Johansson
10/09/2019, 9:43 AMLuca Nicoletti
10/09/2019, 9:44 AMfindViewById
execute before inflating the view will return null
diesieben07
10/09/2019, 9:45 AMLuca Nicoletti
10/09/2019, 9:45 AMids
are different because one is referencing a layoutid
findViewById
is trying to findlayout
is not inflated, findViewById
will return null
NPE
w_bianrytree
10/09/2019, 9:48 AMLuca Nicoletti
10/09/2019, 9:49 AMAlexander Johansson
10/09/2019, 10:14 AMprivate lateinit var myChildView: View
init {
View.inflate(R.layout.my_layout,this)
myChildView = findViewById(R.id.my_view_id)
}
Or even lazily using by lazy {}
Luca Nicoletti
10/09/2019, 10:16 AMwasyl
10/09/2019, 10:40 AMfindViewById
not crashLuca Nicoletti
10/09/2019, 10:45 AMwasyl
10/09/2019, 10:46 AMViewGroup
for example