Sergei Buvaka
Sergei Buvaka

Reputation: 611

View.post vs runnable.run

I have Compound View (ConstraintLayout). Sometimes this View can change its size, and I need change visibility of several views inside parent view.

I do it inside callback onSizeChanged(). If I do it simple, like this:

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        configurator.constraint()
    }

sometimes views doesn't change their visibilty. It can happens quite randomly.

But, if I do it with post{} or doOnPreDraw{}

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        doOnPreDraw { configurator.constraint() }
    }

everything is OK.

I want understand why it's happens. What difference between this to approaches?

Upvotes: 0

Views: 100

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

onSizeChanged() is not called on the main thread, and any updates from other threads to UI are not guaranteed. Synchronizing back to the main thread via post() or doOnPreDraw() fix the issue as you have observed.

Upvotes: 1

Related Questions