Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 ListActivity 做一個文件瀏覽器:ListView 入門實戰

編輯:Android 程式設計入門

學 ListView 最好的方式就是做一個能跑的小工具。這里實現的是一個簡易文件瀏覽器:進入頁面列出根目錄下的文件與文件夾,點擊文件夾進入下一層,點擊文件則彈出提示。麻雀雖小,卻把 ListView 的數據源管理、適配器綁定、項點擊回調三件事都串了起來。

Activity 代碼

public class TestFileActivity extends ListActivity {

    private ArrayList<String> items = null;   // 顯示用的名稱列表
    private ArrayList<String> paths = null;   // 與 items 一一對應的完整路徑
    private String rootPath = "/";
    private TextView mPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mPath = (TextView) findViewById(R.id.mPath);
        mPath.setTextColor(Color.RED);
        getFileDir(rootPath);
    }

    /** 加載指定路徑下的文件列表 */
    private void getFileDir(String filePath) {
        mPath.setText(filePath);
        items = new ArrayList<String>();
        paths = new ArrayList<String>();

        File file = new File(filePath);
        File[] files = file.listFiles();

        // 非根目錄時,加上「返回根目錄」和「返回上一級」兩個特殊項
        if (!filePath.equals(rootPath)) {
            items.add("Back To " + rootPath);
            paths.add(rootPath);
            items.add("Back to ../");
            paths.add(file.getParent());
        }

        if (files != null) {
            for (File temp : files) {
                items.add(temp.getName());
                paths.add(temp.getPath());
            }
        }

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(this, R.layout.file_now, items);
        setListAdapter(adapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        File file = new File(paths.get(position));
        if (file.canRead()) {
            if (file.isDirectory()) {
                getFileDir(paths.get(position));   // 目錄:鑽進去
            } else {
                new AlertDialog.Builder(this)
                        .setTitle("Message")
                        .setMessage("[" + file.getName() + "] is a file")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) { }
                        }).show();
            }
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("Message")
                    .setMessage("操作無效")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) { }
                    }).show();
        }
    }
}

布局文件

main.xml 里有一個顯示當前路徑的 TextView 和一個 ListView。注意 ListView 的 id 必須寫成 @android:id/list,這是 ListActivity 默認尋找列表的約定:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/mPath"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

單項布局 file_now.xml 更簡單,一個 TextView 即可:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="20px"
    android:textSize="14sp" />

從這個例子里能收獲什么

  • File.listFiles() 返回當前目錄下的文件數組,記得判空——路徑不存在或無權限時它會返回 null,直接 for-each 就是空指針。
  • 名稱和路徑用兩個平行的 List 維護,靠下標對應,是最直觀的做法;數據復雜時更推薦封裝一個 Bean 對象。
  • ListActivity 讓列表綁定變得極簡,但也犧牲了布局自由度。真實項目里更常用普通 Activity 加 ListView,配合 BaseAdapter 做視圖復用。
  • 訪問外部存儲需要在清單里申請 READ_EXTERNAL_STORAGE 權限,Android 6.0 以上還要動態申請,否則 listFiles() 只會返回空。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved