[android / Kotlin]: When Are Views Initialized In Lifecycle?
Solution 1:
You can try using viewTreeObserver.
valvto= button.viewTreeObserver
vto.addOnGlobalLayoutListener {
Log.e("Show me width", button.width.toString())
}
It is working, but it can and WILL be called several times!!!
Other option is to use Handler and postDelayed
Handler().postDelayed({
Log.e("Show me width2", button.width.toString())
}, 1000)
Yes, this is very bad practice, but it can save you in stupid situation :)
Good luck!
Solution 2:
I think I finally found the post on SO which provides the background knowledge you're looking for: take a look at View's getWidth() and getHeight() returns 0
As it seems that it's impossible to get the "real" width in onResume()
since the runtime has not yet determined the value at this time, you can set the initial position for your Button
with the help of ViewTreeObserver
.
The following lines from onCreate()
show how to use a OnPreDrawListener
(just to introduce another option):
btPunkte = findViewById(R.id.btnPoints)
btPunkte.setOnClickListener { doPunkt(true) }
btPR1 = findViewById(R.id.btnPR1)
val vto = btPR1.viewTreeObserver
val listener: ViewTreeObserver.OnPreDrawListener = object : ViewTreeObserver.OnPreDrawListener {
var doUpdate: Boolean = trueoverridefunonPreDraw(): Boolean {
if(doUpdate) {
doUpdate = false
btPR1.viewTreeObserver.removeOnPreDrawListener(this)
val width: Int = btPR1.measuredWidth
servOffset = width / 2
anzeigeAktualisieren()
}
returntrue
}
}
vto.addOnPreDrawListener (listener)
Note that besides removing the listener I also use a Boolean
to make sure the position of btPR1 is only modified once (onPreDraw()
will normally be called more often, the exact number seems to depend on the complexity of the surrounding ViewGroup
)
Post a Comment for "[android / Kotlin]: When Are Views Initialized In Lifecycle?"