
Only objects running on the UI thread have access to other objects on
that thread.
也就是说,以下所有示例(例如A..C)都不应该起作用,因为它们试图修改UI线程中的对象.但实际上案例A和B确实访问了UI线程中的对象(TextVIEw).
这里我们从MainActivity开始一个新线程:
protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); new Thread(new ClIEntThread()).start();} 案例A(UI线程中的对象被修改)
class ClIEntThread implements Runnable { public voID run() { final TextVIEw myTextVIEw = (TextVIEw) findVIEwByID(R.ID.myTextVIEw); myTextVIEw.setText("Hello there!"); }} 情况B(UI线程中的对象被多次修改)
class ClIEntThread implements Runnable { public voID run() { final TextVIEw myTextVIEw = (TextVIEw) findVIEwByID(R.ID.myTextVIEw); for (int i=0; i < 600; i++) { myTextVIEw.setText("Hello there!"); } }} 情况C(稍微延迟后,UI线程中的对象未被修改)
class ClIEntThread implements Runnable { public voID run() { final TextVIEw myTextVIEw = (TextVIEw) findVIEwByID(R.ID.myTextVIEw); try {Thread.sleep(900);} catch (InterruptedException e) {}; myTextVIEw.setText("Hello there!"); }} 只有案例C才会抛出异常:
CalledFromWrongThreadException: Only the original thread that created
a vIEw hIErarchy can touch its vIEws.
我错过了什么吗?目前看来,在某些情况下,可以从未在UI线程上运行的线程修改UI线程(如果它发生得足够快).
解决方法 这是一种乐趣.您无法在后台线程中更新UI.但在这种情况下,UI尚未绘制,因此它不会像更新UI那样处理您的代码,而更像是设置值.无论如何,如果您在显示UI后更新它,它将被视为UI更新. 总结以上是内存溢出为你收集整理的android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程全部内容,希望文章能够帮你解决android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)