之前一直想找一个比较好的文件选择的第三方库,可是看了都不太满意。于是就自己做了一个。像这样的一个小的功能,做起来也不是什么难事。但是要做得好看,还是花了一些时间,但这都是值得的。
例图
不多说,先上图:
列举当前目录下的所有文件,如果是选择目录,则不显示文件,如果是选择文件,则需要显示文件。
新建目录,就是在当前路径下新建目录,同时新建后的目录要能够及时显示在文件列表中。
实现的功能
- 文件选择
- 目录选择
- 可显示隐藏文件
- 显示上一次打开目录
- 显示上一级目录
- 显示当前路径
- 文件显示大小和修改时间
- 目录显示子项数量和修改日期
- 新建目录
难点和细节
1. android6.0以上版本动态权限请求
需要读写权限,添加第三方权限请求库:
dependencies {
...
implementation "com.yanzhenjie:permission:2.0.0-rc12"
}
使用:
AndPermission.with(this)
.runtime()
.permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
.onGranted(data1 -> {
new FileChooserDialog()
.setSelectType(FileProvider.TYPE_DIR)
.setOnFileSelectedListener((path -> {
// todo
}))
.show(getSupportFragmentManager());
}).start();
2.文件选择 弹窗继承自DialogFragment,文件列采用RecyclerView
DialogFragment与Dialog有一些不同的地方,其中show方法需要传入FragmentManager
另外需在onCreateVie方法初始化布局,以及获取到控件
public class FileChooserDialog extends DialogFragment{
private final static String TAG = "FileChooserDialog";
private int selectIndex = -1;
private int selectType = FileProvider.TYPE_DIR;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//去掉自带的标题
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View view = inflater.inflate(R.layout.dialog_file_chooser, container);
...
return view;
}
public void show(FragmentManager manager) {
super.show(manager, TAG);
}
...
}
另外就是RecycleView,之所以采用RecycleView,是因为发现如果用ListView,内存会不断增加,很难降下来。
RecyclerView rvFile;
CommonAdapter<FileProvider.FileData> adapter;
...
public void initData() {
rvFile.setLayoutManager(new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false));
mFileProvider = FileProvider.newInstance(getOldPath(), selectType);
adapter = new CommonAdapter<>(getContext(), mFileProvider.list(), R.layout.item_list_file, this::initListItem);
rvFile.setAdapter(adapter);
mTvCurPath.setText("当前路径: " + mFileProvider.getCurPath());
}
其中CommonAdapter继承自BaseAdapter,是通用的Adapter,兼容ListView:
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<CommonHolder> implements ListAdapter, SpinnerAdapter {
protected final List<T> data;
private final DataSetObservable mDataSetObservable = new DataSetObservable();
@Override
public void registerDataSetObserver(DataSetObserver observer) {
mDataSetObservable.registerObserver(observer);
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
mDataSetObservable.unregisterObserver(observer);
}
public void notifyDataChanged() {
mDataSetObservable.notifyChanged();
notifyDataSetChanged();
}
...
}
3. 目录跳转
这一部分逻辑有FileProvider类完成; 这里需要注意的是,有些手机不支持读取根目录,所以改为读取"/mnt/"作为根目录就行读取。
另外跳转目录都是改变当前路径,然后再刷新数据。
public final class FileProvider implements Iterable<FileProvider.FileData> {
public static final int TYPE_DIR = 1;
public static final int TYPE_FILE = 2;
private final String mRootPath;
private final int mType;
private final String mOldPath;
private String curPath;
private boolean mFilter;
private List<FileData> mFileDataList;
public static FileProvider newInstance(String oldPath, int type) {
File rootFile = new File("/");
if (rootFile.exists() && rootFile.list() != null) {
return new FileProvider(type, oldPath, rootFile.getPath());
} else {
rootFile = new File("/mnt/");
if (rootFile.exists() && rootFile.list() != null) {
return new FileProvider(type, oldPath, rootFile.getPath());
} else {
throw new UnsupportedOperationException("");
}
}
}
private FileProvider(int type, String oldPath, String rootPath) {
this.mType = type;
this.mOldPath = oldPath;
this.mRootPath = rootPath;
this.curPath = mRootPath;
this.mFileDataList = new ArrayList<>();
this.mFilter = true;
this.setData();
}
public List<FileData> refresh() {
setData();
return mFileDataList;
}
public List<FileData> setFilter(boolean filter) {
this.mFilter = filter;
setData();
return mFileDataList;
}
public FileData getFileData(File file, FilenameFilter filter, String info) {
boolean isDir = file.isDirectory();
return new FileData(
file.getName(),
isDir,
file.getPath(),
mType == (isDir ? 1 : 2),
info);
}
private String getSizeStr(long size) {
if (size >= 1024 * 1024 * 1024) {
return String.format("%.2f G", (float) size / 1073741824L);
} else if (size >= 1024 * 1024) {
return String.format("%.2f M", (float) size / 1048576L);
} else if (size >= 1024) {
return String.format("%.2f K", (float) size / 1024);
}
return size + "B";
}
@SuppressLint("SimpleDateFormat")
private void setData() {
this.mFileDataList.clear();
FilenameFilter filenameFilter = (dir, name) -> !name.startsWith(".");
File[] files = mFilter ? new File(curPath).listFiles(filenameFilter) : new File(curPath).listFiles();
if (files != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
for (File file : files) {
boolean isDir = file.isDirectory();
String info;
if (isDir) {
int size = 0;
String[] names = mFilter ? file.list(filenameFilter) : file.list();
if (names != null) {
size = names.length;
}
// if (mType == TYPE_FILE && size == 0) continue;
info = size + "项 | " + dateFormat.format(new Date(file.lastModified()));
mFileDataList.add(getFileData(file, filenameFilter, info));
} else if (mType == TYPE_FILE) {
info = getSizeStr(file.length()) +
" | " +
dateFormat.format(new Date(file.lastModified()));
mFileDataList.add(getFileData(file, filenameFilter, info));
}
}
}
Collections.sort(mFileDataList, (o1, o2) -> {
if (o1.isDir == o2.isDir) return o1.name.compareTo(o2.name);
return o2.isDir ? 1 : -1;
});
if (isRoot()) {
if (mOldPath != null && !mOldPath.equals(mRootPath)) {
File oldFile = new File(mOldPath);
if (oldFile.exists()) {
mFileDataList.add(0, new FileData(oldFile.getName(), true, oldFile.getPath(), false, "[上次打开目录] " + oldFile.getPath()));
}
}
} else {
String realPath = new File(curPath).getParent();
mFileDataList.add(0, new FileData("../", true, realPath, false, "[返回上一级] " + realPath));
}
}
public boolean isRoot() {
return curPath.equalsIgnoreCase(mRootPath);
}
public List<FileData> gotoParent() {
if (!isRoot()) {
curPath = new File(curPath).getParent();
setData();
}
return mFileDataList;
}
public List<FileData> gotoChild(int position) {
if (position >= 0 && position < mFileDataList.size() && mFileDataList.get(position).isDir) {
curPath = mFileDataList.get(position).realPath;
}
setData();
return mFileDataList;
}
public FileData getItem(int position) {
return mFileDataList.get(position);
}
public int size() {
return mFileDataList.size();
}
public String getCurPath() {
return curPath;
}
...
}
同时在其内部定义了FileData类:
public static class FileData {
/**
* 文件名称
*/
public final String name;
/**
* 是否为文件夹
*/
public final boolean isDir;
/**
* 真实路径
*/
public final String realPath;
/**
* 是否可选择
*/
public final boolean selectable;
/**
* 文件信息
*/
public final String info;
public FileData(String name, boolean isDir, String realPath, boolean selectable, String info) {
this.name = name;
this.isDir = isDir;
this.realPath = realPath;
this.selectable = selectable;
this.info = info;
}
...
}
4. 文件选择
文件选择,可以通过当前路径路径以及列表索引来唯一确定路径;都是,当跳转目录后,索引应该重置。
这里采用WeakReference记录选择的控件,但选择其他目录或者文件时,之前的控件需要重置一下状态。
...
private void initListItem(CommonHolder holder, FileProvider.FileData data, int position) {
holder.setText(R.id.txt_path, data.name);
holder.setItemOnClickListener(v -> {
if (data.name.equals("../")) {
selectIndex = -1;
refreshData(mFileProvider.gotoParent());
} else {
selectIndex = -1;
refreshData(mFileProvider.gotoChild(position));
}
});
holder.setText(R.id.txt_info, data.info);
if (data.isDir) {
holder.setSrc(R.id.img_file, R.drawable.ic_wenjian);
holder.setVisible(R.id.img_back, View.VISIBLE);
} else {
holder.setSrc(R.id.img_file, R.drawable.ic_file);
holder.setVisible(R.id.img_back, View.GONE);
}
CheckBox checkBox = holder.getView(R.id.checkBox3);
if (checkBox != null) {
checkBox.setVisibility(data.selectable ? View.VISIBLE : View.GONE);
checkBox.setTag(position);
checkBox.setChecked(selectIndex == position);
if (selectIndex == position) {
weakCheckBox = new WeakReference<>(checkBox);
}
checkBox.setOnCheckedChangeListener(this);
}
}
...
5. 源码地址
https://github.com/xiaoyifan6/videocreator
该源码主要用于图片合成gif或者视频,其中文件选择弹窗是自己写的。感觉这个弹出应该有许多地方可以用到,所以写下这篇文章,方便以后参考查看。