开发者

Correct approach to update UI in Android

I'm new to Android stuff. Currently I have someone else code in my hand and I'm trying to understand the functionality. Whoever wrote the code, used Handler and messages in it. For example, if a button is clicked, onClick listener is called which then posts a message to handler. Inside the handler there is a switch case statement which calls different methods based on a data passed in Message what attribute.

My question is, is this a correct approach or we should just call our method directly in the onClick handler.

As i understand, handler should be used to post a message to the main UI thread, from some other thread (worker 开发者_如何学Cthread which pulls data from server).


You are correct. OnClick should already be running in the UI thread and thus there is no need to use a handler. The only times I have used a Handler is for posting callbacks from an OpenGL or timer/worker thread OR when I need a message to be handled in the future.

[update] I will add that if the handler is somehow posting to some non-GUI thread then that might make sense under very particular circumstances but the most common case is for code called from onClick to execute in the GUI thread.


if your method inside button onclick(),is a long running process ,say for a example getting data from server,so it is better to use that method in separate thread.

when the method process is completed ,using handler post message and the proceed further.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜