編輯:關於 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。
上面這個版本可以跑通,但要真正用在項目裡,還需要考慮以下幾點:
READ_EXTERNAL_STORAGE 危險權限,必須做運行時動態申請;Android 11 及以上引入了分區存儲,訪問非媒體文件需要使用 Environment.isExternalStorageManager() 判斷並引導用戶授予「所有文件訪問權限」。/ 開始對普通用戶並不友好,通常應從 Environment.getExternalStorageDirectory() 或 Downloads 目錄起始。MimeType 過濾,避免用戶在幾百個文件中翻找。ellipsize 與 singleLine,否則長名稱會撐開佈局。listFiles() 在主線程執行會造成卡頓,應放到子線程並配合分頁或加載更多。Intent.ACTION_GET_DOCUMENT(Storage Access Framework)。它由系統提供統一的文件選擇介面,無需申請存儲權限,且能訪問雲盤、下載等多種 Provider,用戶體驗與兼容性都遠優於自定義瀏覽器。自定義文件瀏覽器的核心邏輯只有三件事:File.listFiles() 遍歷當前目錄、SimpleAdapter 渲染列表、點擊時用 isDirectory() 判斷是深入還是回傳。整個實現不到一百行代碼。
但從工程角度看,這類功能涉及大量邊界條件與系統版本差異。如果沒有特殊的自定義 UI 需求,優先使用系統的 SAF 會是更省心的選擇;確有必要自研時,則務必把權限、判空、性能與文件名顯示這幾個細節處理到位。
Android UI 自定義控件入門——打造自己的 ImageButton
概述 我們在使用一些 App 時,應該很少看到完全不加修飾的「裸控件」吧?除非是系統內建軟體,為了風格統一而做出權衡。這裡並不是要批評 Android 原生控件不好看——
動手做一個 Android 驗證碼控件:自定義 View 全流程實踐
本文在鴻洋大神《Android 自定義 View(一)》的基礎上做了擴展,同時也整理了不少關於自定義 View 構造函數的細節,適合剛入門自定義控件的同學當作一份完整練手
Android中使用WebSocket實現群聊與消息推送(脫離WebView)
WebSocket是HTML5的一種新協議,它實現了浏覽器與服務器之間的全雙工通信(full-duplex)。作為Web2.0時代的新產物,它用於彌補HTTP協議的某些不
Android 學習筆記:Gallery 畫廊視圖與圖片瀏覽
Gallery 與 Spinner 有著共同的父類 AbsSpinner,這說明兩者本質上都是「列表選擇框」。差別在方向與交互:Spinner 是垂直下拉清單,主要用途是