在 Android 中,实现一个文件选择器(FileChooser)可以通过使用 Intent 来调用系统自带的文件选择器
首先,在你的 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;重写 onActivityResult 方法以处理文件选择结果:@Overrideprotected 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); // ... } }}创建一个辅助方法 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;}当需要打开文件选择器时,调用 openFileChooser() 方法。现在,当用户调用 openFileChooser() 方法时,系统将显示一个文件选择器,用户可以从中选择文件。在 onActivityResult 方法中,你可以处理选中的文件,例如获取文件路径、读取文件内容等。