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

Android 實現文件目錄瀏覽與選擇功能

編輯:關於 Android 程式設計

很多應用都需要「選擇一個文件」的能力:文檔導入、圖片替換、配置文件加載等等。如果每次都要自己寫一套文件瀏覽器,成本不低。本文用最簡潔的方式實現一個可逐級瀏覽目錄、並選中文件的對話框。

一、主介面佈局

activity_main.xml:一個按鈕觸發選擇,一個 TextView 展示結果。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/filedire_button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="選擇文件" />

    <TextView
        android:id="@+id/filedire_textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

</LinearLayout>

二、列表項佈局

adapter.xml:一張圖標加一段文字,圖標用來區分「文件夾」與「文件」,這是最直觀的視覺編碼。

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/adapter_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.48"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/adapter_filename"
            android:layout_width="242dp"
            android:layout_height="match_parent"
            android:text="TextView" />

    </LinearLayout>

</LinearLayout>

三、核心代碼

整個功能的實現依賴 AlertDialog.setAdapter():把文件列表灌給一個對話框,點擊某項時判斷是目錄還是文件,目錄就遞歸進入,文件就回傳路徑。

package com.example.filedirec;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button chooseFile;
    private TextView fileDire;
    private String curPath = new String("/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        chooseFile = (Button) findViewById(R.id.filedire_button1);
        fileDire = (TextView) findViewById(R.id.filedire_textView1);

        chooseFile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                openCurDir(curPath);
            }
        });
    }

    private void openCurDir(String curPath) {
        File f = new File(curPath);
        File[] file = f.listFiles();

        final List<Map<String, Object>> listItem =
                new ArrayList<Map<String, Object>>();

        // 如果不是根目錄,加入「返回上一級」
        if (!curPath.equals("/")) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("name", "返回上一級目錄");
            map1.put("image", R.drawable.back02);
            map1.put("path", f.getParent());
            map1.put("isDire", true);
            listItem.add(map1);
        }

        if (file != null) {   // 必須判空,否則空目錄會報錯
            for (int i = 0; i < file.length; i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", file[i].getName());
                map.put("image", file[i].isDirectory() ? R.drawable.folder : R.drawable.doc);
                map.put("path", file[i].getPath());
                map.put("isDire", file[i].isDirectory());
                listItem.add(map);
            }
        }

        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listItem,
                R.layout.adapter,
                new String[]{"name", "image"},
                new int[]{R.id.adapter_filename, R.id.adapter_image});

        final AlertDialog.Builder b = new Builder(MainActivity.this);
        b.setAdapter(adapter, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                if ((Boolean) listItem.get(arg1).get("isDire")) {
                    // 是目錄,繼續深入
                    openCurDir((String) listItem.get(arg1).get("path"));
                } else {
                    // 是文件,回傳路徑
                    fileDire.setText((String) listItem.get(arg1).get("path"));
                }
            }
        });
        b.show();
    }
}

對話框效果如下:

四、代碼中的關鍵點解析

1. listFiles() 必須判空
File.listFiles() 在目錄不存在、不是目錄、或沒有讀取權限時都會返回 null,而不僅僅是返回空數組。這是新手最容易踩的坑。上面代碼中的 if (file != null) 判斷不能省。

2. 「返回上一級」的實現
通過 f.getParent() 拿到父目錄路徑,並把 isDire 標記為 true,這樣點擊它時會走遞歸分支。同時用 curPath.equals("/") 判斷是否已到根目錄,避免在根目錄下再往上跳出現異常。

3. 遞歸而非新建 Activity 每次點擊目錄都調用 openCurDir 自己,同時 show() 一個新的對話框。這樣的缺點是層級深了之后需要一層層關閉才能退出,體驗不佳。更好的做法是在同一個對話框中調用 adapter.notifyDataSetChanged() 刷新數據,並維護一個路徑棧用於回退。

4. SimpleAdapter 的數據映射
new String[]{"name", "image"} 指定 Map 中的哪些 key 要取出,new int[]{R.id.adapter_filename, R.id.adapter_image} 指定放到哪些控件上,兩者按順序一一對應。這裡把 ImageView 的 id 也放進來,是 SimpleAdapter 的內置能力:當目標控件是 ImageView 時,若值為 int 類型的資源 id,會自動調用 setImageResource。

五、生產環境需要補充的能力

上面這個版本可以跑通,但要真正用在項目裡,還需要考慮以下幾點:

  • 權限處理:Android 6.0 以後讀取外部存儲需要 READ_EXTERNAL_STORAGE 危險權限,必須做運行時動態申請;Android 11 及以上引入了分區存儲,訪問非媒體文件需要使用 Environment.isExternalStorageManager() 判斷並引導用戶授予「所有文件訪問權限」。
  • 起始目錄:硬編碼從 / 開始對普通用戶並不友好,通常應從 Environment.getExternalStorageDirectory() 或 Downloads 目錄起始。
  • 文件篩選:如果只需要選圖片或文檔,應在加入列表前按後綴名或 MimeType 過濾,避免用戶在幾百個文件中翻找。
  • 長文件名處理:TextView 需要設置 ellipsize 與 singleLine,否則長名稱會撐開佈局。
  • 加載性能:目錄下文件成千上萬時,listFiles() 在主線程執行會造成卡頓,應放到子線程並配合分頁或加載更多。
  • 更現代的替代方案:實際項目中強烈建議使用 Intent.ACTION_GET_DOCUMENT(Storage Access Framework)。它由系統提供統一的文件選擇介面,無需申請存儲權限,且能訪問雲盤、下載等多種 Provider,用戶體驗與兼容性都遠優於自定義瀏覽器。

小結

自定義文件瀏覽器的核心邏輯只有三件事:File.listFiles() 遍歷當前目錄、SimpleAdapter 渲染列表、點擊時用 isDirectory() 判斷是深入還是回傳。整個實現不到一百行代碼。

但從工程角度看,這類功能涉及大量邊界條件與系統版本差異。如果沒有特殊的自定義 UI 需求,優先使用系統的 SAF 會是更省心的選擇;確有必要自研時,則務必把權限、判空、性能與文件名顯示這幾個細節處理到位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved