Android + KOTLIN:查找文件夹并将其名称存储为字符串数组 [英] Android + KOTLIN: find folders and store their names as string array
问题描述
我有一个PHP脚本,该脚本能够自动查找文件夹并将其名称作为字符串发送给客户端,以便可以在 innerHTML
按钮中使用它们.我想在Android应用程序中使用Android Studio和Kotlin进行完全相同的操作,但是我没有找到任何特定的方法来完成该操作.
I have a PHP script which has the ability to automatically find folders and send their names to the client as string so that they can be used in innerHTML
buttons. I'd like to do EXACTLY the same thing in my Android app with Android Studio and Kotlin, but I failed to find any specific way to do that.
这是获取所有文件夹名称并将其存储为数组的PHP代码:
Here's the PHP code that fetches all folder names and stores them as an array:
$_SESSION['$folders'] =[] #initiates array
$_SESSION['$folders'] = array_filter(glob('*'), 'is_dir'); #finds subfolders in the root folder and stores their names
但是,文件夹和PHP脚本都在同一目录中,因此除了 array_filter
及其消除参数 glob('*')
和 is_dir
,如您在上面的代码中所见,这就是我在Kotlin中寻找的魔术".
However, both folders and PHP script are in the same directory, so no further path string treatment is required other than array_filter
and its elimination arguments glob('*')
and is_dir
as you can see in the code above, and THAT is the "magic" I'm looking for with Kotlin.
因为似乎我在这里没有足够的声誉而无法发送图片.
Couldn't send pictures because it seems I don't have enough reputation here.
推荐答案
在Android中,您应严格指定要查看的文件夹的路径.起点可以是 Environment.getExternalStorageDirectory()
-主共享/外部存储目录.
In Android you should strictly specify the path of the folder you want to view.
Start point could be Environment.getExternalStorageDirectory()
- the primary shared/external storage directory.
然后,您可以使用方法 dir.listFiles()
获取文件列表.如果您需要以某种方式对其进行过滤(例如,仅具有目录),则可以添加 FileFilter : dir.listFiles(FileFilter {it.isDirectory})
Then you could get list of files with method dir.listFiles()
. If you need to filter it somehow (for example have only directories) you could add a FileFilter: dir.listFiles(FileFilter { it.isDirectory })
另一个重要的事情是,您必须具有读取外部storange的权限.因此,您应该添加到您的 Manifest.xml :
Another important thing is that you have to have a permission for reading external storange. Thus you should add to your Manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
从Android 6.0开始,您还应该请求此权限:
Starting from Android 6.0 you should additionally ask for this permission:
Fragment.requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), READ_STORAGE_RC)
并在 Fragment.onRequestPermissionsResult 方法中处理结果.
我创建了如何一起使用的示例.您需要创建活动并在其中添加一个片段: DirListFragment
I created example of how it could be used together. You need to create activity and add a Fragment inside: DirListFragment
class DirListFragment : Fragment() {
private val adapter by lazy { DirListAdapter { dir = it } }
private var dir: File by observable(Environment.getExternalStorageDirectory()) { _, _, _ -> onNewParent() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_dir_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
checkPermissionReadStorage(requireActivity())
list.adapter = adapter
up.setOnClickListener { dir = dir.parentFile }
onNewParent()
}
private fun onNewParent() {
parent.text = dir.absolutePath
adapter.items = dir.listFiles(FileFilter { it.isDirectory })?.toList() ?: emptyList()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == READ_STORAGE_RC && permissionGranted(requireActivity())) onNewParent()
}
private fun checkPermissionReadStorage(activity: Activity) {
if (!permissionGranted(activity)) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), READ_STORAGE_RC)
}
}
private fun permissionGranted(activity: Activity) =
ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
private companion object {
const val READ_STORAGE_RC = 123
}
}
DirListAdapter
class DirListAdapter(private val clickListener: (file: File) -> Unit) :
RecyclerView.Adapter<DirListAdapter.ViewHolder>() {
var items by Delegates.observable(listOf<File>()) { _, _, _ -> notifyDataSetChanged() }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(parent)
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.caption.text = items[position].name
holder.caption.setOnClickListener { clickListener(items[position]) }
}
class ViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder
(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false)) {
val caption: TextView = itemView.findViewById(android.R.id.text1)
}
}
fragment_dir_list.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/up"
android:text="UP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/up"
android:layout_marginBottom="8dp"
android:singleLine="true"
android:ellipsize="start"
tools:text="Parent dir"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
android:layout_below="@id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</RelativeLayout>
希望这将有助于您了解基础.
Hope this will help to understand the basis.
这篇关于Android + KOTLIN:查找文件夹并将其名称存储为字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!