一个简单的Android文件浏览器:
public class FileList extends ListActivity
{
private List<String> items = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.directory_list);
fill(new File("/").listFiles());
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
int selectionRowID = (int) id;
if (selectionRowID == 0)
{
fillWithRoot();
}
else
{
File file = new File(items.get(selectionRowID));
if (file.isDirectory())
{
fill(file.listFiles());
}
else
{
//AlertDialog.show(this, "Not a Directory","That's a file, not a directory", "Cancel", false);
Intent result = new Intent();
result.putExtra("filename", file.getName());
setResult(RESULT_OK, result);
finish();
}
}
}
private void fillWithRoot() {
fill(new File("/").listFiles());
}
private void fill(File[] files)
{
if(files == null)
return;
items = new ArrayList<String>();
items.add(getString(R.string.to_top));
for (File file : files)
items.add(file.getName());
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,
R.layout.file_row, items);
setListAdapter(fileList);
}
}
其中的布局文件为
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ListView
android:id="@id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_files"
/>
</LinearLayout>
需要添加的权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>