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.diesieben07
10/09/2019, 9:31 AMfun 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)
}
}
diesieben07
10/09/2019, 9:31 AMLuca Nicoletti
10/09/2019, 9:32 AMdiesieben07
10/09/2019, 9:32 AMdiesieben07
10/09/2019, 9:32 AMw_bianrytree
10/09/2019, 9:33 AMdiesieben07
10/09/2019, 9:34 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 AMdiesieben07
10/09/2019, 9:39 AMw_bianrytree
10/09/2019, 9:40 AMdiesieben07
10/09/2019, 9:43 AMdiesieben07
10/09/2019, 9:43 AMAlexander Johansson
10/09/2019, 9:43 AMLuca Nicoletti
10/09/2019, 9:44 AMLuca Nicoletti
10/09/2019, 9:44 AMfindViewById
execute before inflating the view will return null
diesieben07
10/09/2019, 9:45 AMdiesieben07
10/09/2019, 9:45 AMLuca Nicoletti
10/09/2019, 9:45 AMids
are different because one is referencing a layoutLuca Nicoletti
10/09/2019, 9:46 AMid
findViewById
is trying to findLuca Nicoletti
10/09/2019, 9:46 AMlayout
is not inflated, findViewById
will return null
Luca Nicoletti
10/09/2019, 9:46 AMNPE
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 AMwasyl
10/09/2019, 10:42 AMwasyl
10/09/2019, 10:44 AMfindViewById
not crashLuca Nicoletti
10/09/2019, 10:45 AMLuca Nicoletti
10/09/2019, 10:45 AMwasyl
10/09/2019, 10:46 AMViewGroup
for example