FileBrowser.java
private List<String> items = null;
private List<String> paths = null;
private String rootPath = "/";
private TextView mPath;
private ListView listView1;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.file_browser);
mPath = (TextView) findViewById(R.id.textView1);
listView1 = (ListView) findViewById(R.id.listView1);
getFileDir(rootPath);
}
/* 取得文件架构的method */
private void getFileDir(String filePath) {
/* 设定目前所在路径 */
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(filePath);
File[] files = f.listFiles();
if (!filePath.equals(rootPath)) {
/* 第一笔设定为[回到根目录] */
items.add("返回根目录");
paths.add(rootPath);
/* 第二笔设定为[回上层] */
items.add("返回上一层");
paths.add(f.getParent());
}
/* 将所有文件加入ArrayList中 */
for (int i = 0; i < files.length; i++) {
File file = files[i];
items.add(file.getName());
paths.add(file.getPath());
}
/*
* 声明一ArrayAdapter,使用file_row这个Layout, 并将Adapter设定给此ListActivity
*/
ArrayAdapter<String> listItemAdapter = new ArrayAdapter<String>(this, R.layout.list_item2, items);
listView1.setAdapter(listItemAdapter);
listView1.setOnItemClickListener(new ListView.OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
File file = new File(paths.get(arg2));
if (file.canRead()) {
if (file.isDirectory()) {
/* 如果是文件夹就再进去读取 */
getFileDir(paths.get(arg2));
} else {
/* 如果是文件,则弹出AlertDialog */
new AlertDialog.Builder(FileBrowser.this)
.setTitle("Message")
.setMessage("[" + file.getName() + "] is File!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
} else {
/* 弹出AlertDialog显示权限不足 */
new AlertDialog.Builder(FileBrowser.this)
.setTitle("Message")
.setMessage("权限不足!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
});
}
file_browser.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@color/white"> <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black"></TextView> <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="fill_parent" android:cacheColorHint="#00000000"></ListView> </LinearLayout>