我正在为android的文件管理器工作,我在列表视图中显示文件/文件夹。此时我想显示文件夹的图标和文件的不同图标。我试图使用File方法isDirectory()和isFile()区分两者,但它们只是作为文件出现..除非我导航到根目录,在这种情况下它工作正常。不知道我哪里出错了,这是代码:
public class DisplayDirectoryActivity extends Activity {
List<Map<String, String>> currentFileList = new ArrayList<Map<String, String>>();
String path;
String query;
ListView lv;
SimpleAdapter simpleAdpt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_directory_activity);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive current directory path
String currentPath = (String) getIntent().getCharSequenceExtra("currentPath");
path = currentPath;
// Add all directories on card to List->Map for display in listview
populateFiles();
// Create ListView attached to ListView in xml definition
lv = (ListView) findViewById(R.id.listView);
// Create a new adapter with the files needed to be listed
simpleAdpt = new SimpleAdapter(getBaseContext(), currentFileList,
R.layout.list_view_adapter, new String[] { "file", "img" },
new int[] { R.id.file, R.id.img });
// Set the new adapter to the ListView
lv.setAdapter(simpleAdpt);
@Override
public void populateFiles() {
// Clear list for updating
currentFileList.clear();
// Create a file from the current path
File current = new File(this.path);
// Array of the files within the current directory
String[] subFiles = current.list();
// Add each file in the current directory to currentFileList
for (int i = 0; i < subFiles.length; i++) {
currentFileList.add(createEntry("file", subFiles[i]));
}
}
// Create a map of key to filename for adding to the currentFileList
private HashMap<String, String> createEntry(String type, String name) {
HashMap<String, String> entry = new HashMap<String, String>();
File current = new File(name);
//If the current file is a directory, display icon as folder
if (current.isDirectory()) {
entry.put(type, name);
entry.put("img", String.valueOf(R.drawable.folder));
}
//If the current file is not a directory, display icon as a file
else {
entry.put(type, name);
entry.put("img", String.valueOf(R.drawable.file));
}
return entry;
}
编辑:createEntry()中的文件是用错误的参数构造的,问题已修复。