求大神帮忙详细说明一下这段代码,并注释一下吧

2025-02-26 17:00:05
推荐回答(1个)
回答1:

public class ListAllFileActivity extends ListActivity {

private List fileList;
private Bundle bundle;
private String fileNameKey = "fileName";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获取存储卡路径
File path = android.os.Environment.getExternalStorageDirectory();
//创建存储卡下data目录的引用
File BuildDir = new File(path, "/data");
//索引data目录下的所有文件
File[] f = BuildDir.listFiles();
//填充到ListView中
fill(f);
}
/**
* @param files data目录下的所有文件引用
*/
private void fill(File[] files) {
//创建文件集合
fileList = new ArrayList();
//循环遍历所有的文件
for (File file : files) {
//判断文件或目录是否有效(过滤文件)
if (isValidFileOrDir(file)) {
//添加在List中
fileList.add(file);
}
}
//创建ListView的adapter
ArrayAdapter fileNameList = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
fileToStrArr(fileList) );
//设置Adapter
setListAdapter(fileNameList);
}
//过滤文件
private boolean isValidFileOrDir(File fileIn)
{
//是否是目录
if (fileIn.isDirectory()) {
return true;
}
else {
//是否是txt文件
String fileNameLow = fileIn.getName().toLowerCase();
if (fileNameLow.endsWith(".txt")) {
return true;
}
}
return false;
}
//文件集合转字符串数组
private String[] fileToStrArr(List fl)
{
ArrayList fnList = new ArrayList();
for (int i = 0; i < fl.size(); i++) {
String nameString = fl.get(i).getName();
fnList.add(nameString);
}
return fnList.toArray(new String[0]);
}

//ListView的item的点击事件
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//获取到点击的item
File file = fileList.get(position);
//判断是否是目录
if (file.isDirectory())
{
//如果是目录则继续索引该目录下的文件
File[] f = file.listFiles();
//填充到ListView
fill(f);
}
else {
//不是目录,则把已选中的文件设置到intent中带到ViewFile这个Activity中
Intent intent = new Intent(ListAllFileActivity.this, ViewFile.class);
bundle = new Bundle();
bundle.putString(fileNameKey, file.getAbsolutePath());
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
}

已注释,给分吧