UI更新及消息处理机制
ps:最近学习的知识太广而没深入了解,全因工作紧张,要短期内全面了解android,没办法只有走马观花,一睹android全貌。由于只是一扫而过,心中只留下概念,没有明白原理,故用到时又得google,特花精力和时间,所以自己决定,把学习过程中点滴全记录在博客上,方便自己用时查找,同时也方便感兴趣的朋友学习。the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
For example, below is some code for a click listener that downloads an image from a separate thread and displays it in an ImageView:
public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.png"); mImageView.setImageBitmap(b); } }).start();}
To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
1.Activity.runOnUiThread(Runnable)
2.View.post(Runnable)
3.View.postDelayed(Runnable, long)
4.Using AsyncTask
5.android.view.View.postInvalidate()
Cause an invalidate to happen on a subsequent cycle through the event loop.
public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start();}
Looper,Handler,Message源码分析
更新UI界面一
更新UI界面二
google官方关于UI更新及线程
invalidate()和postInvalidate() 的区别及使用
Android自定义View中界面刷新的方法 nvalidate()和postInvalidate() 的区别及使用
页:
[1]