7

I m coding some ui screens on android. sometime I need to see ui changes immediately, but that changes can be seen on next ui thread request. so, for example if I remove a view on screen and add another view programmatically, then change whole view (with viewAnimator), removing view can be observed, but new view can not be observed. I m sure new view is added, because when I go back to first page, new view is on screen.

which function should I call add or remove some view on screen to see its effect immediatlety ?

I tried invalidate(), but it doesnt work for my case

Adem
  • 9,402
  • 9
  • 43
  • 58

3 Answers3

6

It sounds like, if you say the UI only updates on the next UI thread request, that you are modifying UI elements from another thread. Therefore, you must modify them in a Runnable using runOnUiThread. So, for example:

//example code
//where you are trying to modify UI components, do this instead
runOnUiThread(new Runnable(){
    public void run(){
        //update UI elements
    }
});
dennisdrew
  • 4,399
  • 1
  • 25
  • 25
2

The best way to ensure that a change will be made to a view as soon as the view is ready is to add a Runnable to the view's message queue:

view.post(new Runnable(){
    @Override
    public void run() {
        //TODO your code
    }
});
Phil
  • 35,852
  • 23
  • 123
  • 164
  • Thanks for the tip, Phil. Never thought about posting it in the view's message queue. – dennisdrew Sep 26 '12 at 13:57
  • I'm setting `isActivated` on a button if the checkbox is checked but, even with your code or the other answer, if I click fast on the checkbox, the button could be deactivated even if the checkbox is checked. – Dr.jacky Oct 12 '20 at 16:20
-2

invalidate() on views that have no drawable (even transparen) or no children is not called. You have to at setBackgroundDrawable(Color.Transparent) to all of them or add a dummy child view at development to observe changes.

Also notice that at Android 3 + the rendering system has changed. When you invalidate parent the children are not always invalidated. You should invalidate the whole tree manually if you want the same beahvior as lower versions

weakwire
  • 9,284
  • 8
  • 53
  • 78
  • it didnt work at all. but it is closest answer I think. I solved my problem in different way – Adem Sep 26 '12 at 08:43
  • Any input on my answer? I think that is the best practice, and most efficient way of doing things. – dennisdrew Sep 26 '12 at 13:55
  • invalidate() should not be called as a means to update views. See the top answer here: http://stackoverflow.com/questions/1458047/why-isnt-view-invalidate-immediately-redrawing-the-screen-in-my-android-game. "View#invalidate tells the system to redraw (via onDraw) the view as soon as the main thread goes idle." This sounds like quite the opposite of what Adem asked, which is real time updates to the UI, rather than waiting for thread operations. – dennisdrew Sep 27 '12 at 15:03