本例子参考SDK开发范例大全
说明:以ListActitivy显示文件列表,以TextView来显示当前路径,再搭配java.io.File来实现手机版的资源管理器
FileSerarchActivity.java
package com.chaowen;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FileSerarchActivity extends ListActivity {
/**
* 对象声明
* items:存放显示的名称
* paths:存放文件路径
* rootPath:起始目录
*/
private List<String> items = null;
private List<String> paths = null;
private String rootPath = "/";
private TextView mPath ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPath = (TextView)findViewById(R.id.mPath);
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("Back to "+rootPath);
paths.add(rootPath);
/*第二条设置为[回上层]*/
items.add("Back to ..");
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> fileList = new ArrayAdapter<String>(this,R.layout.file_row,items);
setListAdapter(fileList);
}
//设置ListItem被单击时要做的动作
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if(file.isDirectory()){
//如果是文件夹就再进一次
getFileDir(paths.get(position));
}else{
//如果是文件,则跳出AlertDialog
new AlertDialog.Builder(this).setIcon(R.drawable.icon)
.setTitle("["+file.getName()+"] is File!")
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
main.xml
<?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"
android:orientation="vertical"
>
<TextView
android:id="@+id/mPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px"
android:textSize="18sp"
android:textColor="@drawable/blue"
>
</TextView>
<ListView
android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
file_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/text1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50px"
android:textSize="20sp"
>
</TextView>