How to force a view to redraw immediately before the next line of code is executed

后端 未结 3 1366
南旧
南旧 2021-01-07 18:46

I have a LinearLayout that I would like to change the background color of when one of its child views (an ImageButton) is clicked. I am able to do this, but not immediately

相关标签:
3条回答
  • 2021-01-07 19:04

    make the changes and call listview.invalidate(); to reflect those changes on UI

    0 讨论(0)
  • 2021-01-07 19:17

    Okay, I finally found a solution to this issue, and it's simple. It seems that the problem was just that I was executing the drawable changes in an OnClickLIstener, when I should have been doing it in an OnTouchListener. If I set an OnTouchListener for my button that looks for ACTION_DOWN and then runs setBackgroundColor on its parent layout, the change occurs immediately.

    An alternative, less robust solution comes from this post. You can assign a selector for the parent layout background in xml, then in the OnTouchListener mentioned above, run setPressed(true) on that layout. It's not a great solution because the selector gives you a lot less freedom than directly changing the view's properties in code. You couldn't set the layout background to a different color by pressing a different button, for example.

    Thanks to those who helped out with suggestions on this!

    0 讨论(0)
  • 2021-01-07 19:25

    You might try forceLayout() with a call to draw(canvas) immediately after. If you did not override onLayout(), onMeasure, draw() or onDraw(), then the default implementation will run. The only issue with this is that you have to either get the Canvas or create one manually.

    It is strongly discouraged to pursue this approach as Android is specifically designed to avoid drawing outside of normal updates. While you are correct that invalidate() does not happen immediately, it is the safest and best way to encourage a redraw. If you want to handle drawing outside of updates, Android provides a way to do that with the SurfaceHolder class.

    0 讨论(0)
提交回复
热议问题