Skip to content

5. 自定义文件类型 Custom your file type

rosuH edited this page Jun 25, 2020 · 4 revisions

如果默认的文件类型无法满足您的需求,您只需要简单三步即可实现您自己的文件类型,并进行检测和过滤操作。 If the default file types don't meet your needs, you can implement your own file types, detection and filtering in three simple steps.

1. 自定义文件类型(Customize your file type)

/**
    * 1. 自定义文件类型。通过路径或文件名来判断是否符合类型
    * 1. Customize the file type. Determine if it matches the type by path or filename.
    */
class CustomFileType(
    override val fileType: String = "",
    override val fileIconResId: Int = R.drawable.ic_unknown_file_picker
) : FileType {
    override fun verify(fileName: String): Boolean {
        return fileName.endsWith("123")
    }
}

2. 自定义文件检测器(Custom file detector)

/**
    * 2. 自定义文件检测器。
    * 检测是否符合您的类型,如果是,那么填充到[FileItemBeanImpl.fileType]中
    * 2. Custom file detector.
    * detects if it matches your type, and if so, then fill it into [FileItemBeanImpl.fileType]
    */
class CustomFileDetector : AbstractFileDetector() {
    private val customFileType by lazy { CustomFileType() }

    override fun fillFileType(itemBeanImpl: FileItemBeanImpl): FileItemBeanImpl {
        // detected file type by yourself and fill your type to [FileItemBeanImpl]
        if (customFileType.verify(itemBeanImpl.fileName)) {
            itemBeanImpl.fileType = customFileType
        }
        return itemBeanImpl
    }
}

3. 使用(Using them)

FilePickerManager
    .from(this@SampleActivity)
    // 1. 使用自定义文件检测器来检测类型,并赋值给  [FileItemBeanImpl.fileType] 属性
    // 1. Using detector detect file's type and fill it into [FileItemBeanImpl.fileType]
    .customDetector(CustomFileDetector())
    .filter(object : AbstractFileFilter() {
        override fun doFilter(listData: ArrayList<FileItemBeanImpl>): ArrayList<FileItemBeanImpl> {
            // 2. 接收结果列表,然后过滤出您想要的类型
            // 2. Receive result list and filter what you want
            listData.removeAll {
                (it.fileType !is CustomFileType) && !it.isDir
            }
            return listData
        }
    })
    .showHiddenFiles(true)
    .forResult(FilePickerManager.REQUEST_CODE)
Clone this wiki locally