传递给List的ArrayAdapter的arraylist是否应该是线程安全的? [英] Should the arraylist passed to an ArrayAdapter of a List be thread-safe?

查看:276
本文介绍了传递给List的ArrayAdapter的arraylist是否应该是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们传递给自定义数组适配器的数组列表是否应该以线程安全的方式对其进行修改?
我的意思是如果我有private class MyAdapter extends ArrayAdapter<CustomObject>并用CustomObjectArrayList实例化它,如果以后我想修改该数组列表或数组列表中的对象以便随后通知适配器UI应该更新的话我应该以线程安全的方式执行此操作吗?例如.通过同步数组列表?

The array list we pass to a custom array adapter are we supposed to modify it in a thread safe way?
I mean if I have private class MyAdapter extends ArrayAdapter<CustomObject> and I instantiate it with my ArrayList of CustomObjects if I later want to modify that array list or objects in the array list in order to then notify the adapter that the UI should be updated should I do it in a thread safe way? E.g. passing a synchronized array list?

推荐答案

如果您修改主/UI线程上的列表,请继续. ListView本身也可以在UI线程上运行.

If you modify the list on the main/UI thread, then go ahead. The ListView itself operates also on the UI thread.

如果从另一个线程更改列表,则可能必须处理同步问题.虽然在ListView不滚动时它不会引起任何问题,即不访问适配器.

If you change the list from another thread, you may have to handle synchronization issues. Though it should not cause any problems when the ListView is not scrolling, i.e. does not access the Adapter.

要随时从另一个线程更改列表,必须将所有更改发布到UI线程.

To change the list anytime from another thread, you have to post all changes to the UI thread.

// this code is executed in another thread
// e.g. download some data
// determine which list elements get changed

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // change th actual list here and notifyDataSetChanged()
    }
});

如果无法确定需要更改哪些元素太复杂,您还可以创建一个新列表和一个新适配器:

If it's too complicated to determine what elements need to change, you also could create a new list and a new adapter:

// this code is executed in another thread
// e.g. download some data
// create a new list and/or a new adapter
final MyAdapter adapter = new MyAdapter(...);

// post to UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        // set the new adapter to the ListView
        listview.setAdapter(adapter);
    }
});

这篇关于传递给List的ArrayAdapter的arraylist是否应该是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆