package com.example.fileasynctaskproject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private ListView mylist=null;
private List<Map<String,Object>> filelist=new ArrayList<Map<String,Object>>();
private SimpleAdapter simple=null;
private ListFileThread tf=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.mylist=(ListView)super.findViewById(R.id.mylist);
File file=new File(java.io.File.separator);//从根目录下开始列出
this.tf=new ListFileThread();
tf.execute(file);
this.mylist.setOnItemClickListener(new OnItemClickListenerlmpl());
}
private class OnItemClickListenerlmpl implements OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
File currFile=(File)MainActivity.this.filelist.get(arg2).get("name");
if(currFile.isDirectory()){
MainActivity.this.filelist=new ArrayList<Map<String,Object>>();
ListFileThread tft=new ListFileThread();
tft.execute(currFile);
}
}
}
private class ListFileThread extends AsyncTask<File, File, String>{
@Override
protected void onProgressUpdate(File... values) {
Map<String,Object> map=new HashMap<String, Object>();
if(values[0].isDirectory()){//如果是目录
map.put("img", R.drawable.folder_close);//设置文件夹图标
}else{
map.put("img", R.drawable.file);//设置文件图标
}
map.put("name", values[0]);
MainActivity.this.filelist.add(map);
MainActivity.this.simple=new SimpleAdapter(
MainActivity.this,
MainActivity.this.filelist,
R.layout.file_out,
new String[]{"img","name"},
new int[]{R.id.img,R.id.name});
MainActivity.this.mylist.setAdapter(MainActivity.this.simple);
}
@Override
protected String doInBackground(File... params) {
if(!params[0].getPath().equals(java.io.File.separator)){//不是根目录
Map<String,Object> map=new HashMap<String, Object>();
map.put("img", R.drawable.folder_open);
map.put("name", params[0].getParentFile());
MainActivity.this.filelist.add(map);
}
if(params[0].isDirectory()){//路径是目录
File tempFile[]=params[0].listFiles();
if(tempFile!=null){
for (int i = 0; i < tempFile.length; i++) {
this.publishProgress(tempFile[i]);
}
}
}
return "执行完毕";
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}