溫馨提示×

Android FileChooser如何實現

小樊
152
2024-09-15 22:40:07
欄目: 編程語言

在 Android 中,實現一個文件選擇器(FileChooser)可以通過使用 Intent 來調用系統自帶的文件選擇器

  1. 首先,在你的 Activity 或 Fragment 中創建一個方法來啟動文件選擇器:
private void openFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "選擇文件"),
                FILE_PICK_REQUEST_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "請安裝文件管理器", Toast.LENGTH_SHORT).show();
    }
}

這里的 FILE_PICK_REQUEST_CODE 是一個整數常量,用于標識文件選擇請求。你可以根據需要設置一個值,例如:

private static final int FILE_PICK_REQUEST_CODE = 1;
  1. 重寫 onActivityResult 方法以處理文件選擇結果:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == FILE_PICK_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
        Uri uri = data.getData();
        if (uri != null) {
            // 在這里處理選中的文件,例如獲取文件路徑、讀取文件內容等
            String filePath = getPathFromUri(this, uri);
            // ...
        }
    }
}
  1. 創建一個輔助方法 getPathFromUri 以獲取文件的路徑:
public String getPathFromUri(Context context, Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = null;

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(columnIndex);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return null;
}
  1. 當需要打開文件選擇器時,調用 openFileChooser() 方法。

現在,當用戶調用 openFileChooser() 方法時,系統將顯示一個文件選擇器,用戶可以從中選擇文件。在 onActivityResult 方法中,你可以處理選中的文件,例如獲取文件路徑、讀取文件內容等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女