Android Studio:点击按钮获取指定文件夹文本文件并在新Activity展示
Got it, let's walk through exactly how to build this feature in Android Studio. I'll split it into actionable steps with code snippets you can adapt directly to your project.
First, you need to handle storage access because we're reading from external storage. The permissions vary a bit depending on your target Android version:
Add Permissions to AndroidManifest.xml
Add these lines inside the <manifest> tag (before <application>):
<!-- For Android 12 and below --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- For Android 13+ (covers most media/file types, including text files) --> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" /> <!-- Alternative for Android 13+ if you only need text files --> <!-- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> -->
Request Permissions Dynamically
In your main Activity, add code to check and request permissions when the user taps the "Open" button:
private val REQUEST_STORAGE_PERMISSION = 1001 private fun checkStoragePermission(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ContextCompat.checkSelfPermission( this, Manifest.permission.READ_MEDIA_IMAGES ) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission( this, Manifest.permission.READ_MEDIA_VIDEO ) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission( this, Manifest.permission.READ_MEDIA_AUDIO ) == PackageManager.PERMISSION_GRANTED } else { ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED } } private fun requestStoragePermission() { val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arrayOf( Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_AUDIO ) } else { arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) } ActivityCompat.requestPermissions(this, permissions, REQUEST_STORAGE_PERMISSION) } // Handle permission request result override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_STORAGE_PERMISSION) { if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) { fetchAndDisplayFiles() } else { Toast.makeText(this, "Storage permission is required to access your notes", Toast.LENGTH_SHORT).show() } } }
In your main Activity's onCreate method, set up the click listener for your "Open" button:
val openButton = findViewById<Button>(R.id.btn_open) openButton.setOnClickListener { if (checkStoragePermission()) { fetchAndDisplayFiles() } else { requestStoragePermission() } }
Create a helper method to get all .txt files from /storage/emulated/0/Notes:
private fun getTextFilesInNotesDir(): List<File> { val notesDir = File(Environment.getExternalStorageDirectory(), "Notes") val textFiles = mutableListOf<File>() if (notesDir.exists() && notesDir.isDirectory) { notesDir.listFiles()?.forEach { file -> if (file.isFile && file.name.endsWith(".txt", ignoreCase = true)) { textFiles.add(file) } } } else { Toast.makeText(this, "Notes directory not found", Toast.LENGTH_SHORT).show() } return textFiles }
First, create a new Activity called FileListActivity (right-click your package > New > Activity > Empty Views Activity).
Layout for FileListActivity (activity_file_list.xml)
Use a ScrollView with a vertical LinearLayout to hold dynamically created TextViews:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <LinearLayout android:id="@+id/ll_file_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gap="12dp"/> </ScrollView>
Code for FileListActivity
In FileListActivity.kt, receive file paths and generate TextViews for each file:
class FileListActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_file_list) val fileContainer = findViewById<LinearLayout>(R.id.ll_file_container) val filePaths = intent.getStringArrayListExtra("FILE_PATHS") filePaths?.forEach { filePath -> val file = File(filePath) val fileTextView = TextView(this).apply { text = """ File Name: ${file.name} Size: ${file.length() / 1024} KB Last Modified: ${SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(file.lastModified()))} Path: ${file.absolutePath} """.trimIndent() textSize = 14f setPadding(16, 16, 16, 16) setBackgroundResource(R.drawable.file_item_bg) // Optional: add a subtle background layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) } fileContainer.addView(fileTextView) } ?: run { val emptyTextView = TextView(this).apply { text = "No text files found in Notes directory" textSize = 16f gravity = Gravity.CENTER layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ) } fileContainer.addView(emptyTextView) } } }
(You can create a simple file_item_bg.xml drawable for the TextView background, or skip this step if you don't need styling.)
Update the fetchAndDisplayFiles() method in your main Activity to send file paths to FileListActivity:
private fun fetchAndDisplayFiles() { val textFiles = getTextFilesInNotesDir() if (textFiles.isNotEmpty()) { val filePaths = textFiles.map { it.absolutePath } as ArrayList<String> val intent = Intent(this, FileListActivity::class.java) intent.putStringArrayListExtra("FILE_PATHS", filePaths) startActivity(intent) } else { Toast.makeText(this, "No text files found in Notes directory", Toast.LENGTH_SHORT).show() } }
- If you expect a large number of files, swap the
LinearLayoutapproach with aRecyclerView—it's more efficient for long lists since it reuses views instead of creating new ones. - Always handle edge cases: missing directories, empty file lists, and permission denials to keep the user experience smooth.
- For Android 10+ (API 29), you can use scoped storage instead of traditional external storage, but the above code works for most common use cases.
内容的提问来源于stack exchange,提问作者abeni

