Android Listview-在线程上加载每一行



在java中,是否可以对listview中的每一行进行多线程处理?我的列表项是来自文件的描述,当有数百个文件时,加载时间太长。我希望它是多线程的,这样我就可以一个接一个地看到加载的项目。

这是我的密码。

Controller_Listrecord adapter;
ListView lstposts = (ListView) findViewById(R.id.lstviewrecordlist);
ArrayList<HashMap<String,String>> details = new ArrayList<HashMap<String, String>>();
File f2 = new File(getFilesDir().getAbsolutePath()); // The location where you want your WAV file
File[] files = f2.listFiles();
String text="";
HashMap<String,String> map=null;
for(int i=0;i<files.length;i++){
byte[] data = Base64.decode(files[i].getName(), Base64.DEFAULT);
try {
text = new String(data, "UTF-8");
//text = files[i].getName();
map = new HashMap<String,String>();
File file = new File(getFilesDir().getAbsolutePath()+"/"+files[i].getName());
mplayer = MediaPlayer.create(this, Uri.parse(getFilesDir().getAbsolutePath()+"/"+files[i].getName()));

Date lastModDate = new Date(file.lastModified());

map.put("recordingtitle",text);
map.put("recordingduration", mplayer.getDuration()+"");
String thedate ;//= DateFormat.getDateInstance(DateFormat.FULL).format(lastModDate);
thedate = android.text.format.DateFormat.format("MMMM dd, yyyy, hh:mm a", lastModDate)+"";
map.put("recordingdate",thedate);
details.add(map);
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
}
adapter = new Controller_Listrecord(this,details);
lstposts.setAdapter(adapter);

假设您有

ArrayAdapter<String> adapter;

然后你可以添加一个同步功能(以避免冲突(,将一个项目添加到适配器:

public synchronized void addItemToList(String item){
adapter.add(item);
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}

然后在每次收到项目时,在线程中调用该函数:

public void runOnBackground(){
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
String item = getItemFromSomwhere();
addItemToList(item);
}
}
}).start();
}

最新更新