废话不多说,上代码片,望大家多支持
public class TestActivity extends Activity {
MAdapter mAdapter;
ArrayList
listStr = new ArrayList
();
ListView lView;
EditText editText;
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
mAdapter.notifyDataSetChanged();// 动态更新ListView
break;
default:
break;
}
};
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("异步加载DEMO(扫描SD卡指定后缀文件)");
Button btnPhoto = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.edittext);
lView = (ListView) findViewById(R.id.lv);
listStr = new ArrayList
();
mAdapter = new MAdapter(listStr, this);
lView.setAdapter(mAdapter);
btnPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread() {
public void run() {
GetFiles(Environment.getExternalStorageDirectory(),editText.getText().toString().trim());
};
}.start();
}
});
}
/**
* 获取文件列表
*
* @param filePath
*/
public void GetFiles(File filePath, String keyWord) {
File[] files = filePath.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file=files[i];
if (file.isDirectory())// files[i]表示的是一个目录则返回true
{
GetFiles(file, keyWord);
} else {
if (file.getName().toLowerCase().contains(keyWord.toLowerCase())) {
FileToStr(file);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.sendEmptyMessage(0);
}
}
}
}
}
public void FileToStr(File f) {
String nameString = f.getName();
listStr.add(nameString);
}
}
public class MAdapter extends BaseAdapter {
ArrayList
list;
Context context;
LayoutInflater inflater;
public MAdapter(ArrayList
list,Context context) { // TODO Auto-generated constructor stub this.context = context; this.list = list; inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView textView = null; if (convertView == null) { convertView = inflater.inflate(R.layout.list, null); } textView = (TextView)convertView.findViewById(R.id.tv); textView.setText(list.get(position).toString()); return convertView; } }