開發環境:Android Studio
庫文件下載:compile 'li.filechoose:FileDirChoose:1.0.3'(可以看一下Android Studio3.0 關鍵字 compile 和 implementation 的區別,有坑)
github地址:https://github.com/zw21544182/RecordDemo(filechoose)
關鍵知識:RecyclerView.Adapter的使用
最終效果:
界面代碼比較簡單,就不貼了
先來看看初始化權限
private void initData() {
if (Build.VERSION.SDK_INT >= 23) {//判斷系統版本是否大於6.0
if (checkSelfPermission(NEED_PERMISSION) == PackageManager.PERMISSION_GRANTED) {
//檢查是否有讀寫權限
loadDataFrompATH(mPath);//從路徑中加載數據
} else {
requestPermissions(new String[]{NEED_PERMISSION}, REQUESCODE);//申請權限
}
return;
}
loadDataFrompATH(mPath);//系統版本小於6.0直接加載數據
}
接下來是加載數據方法
private void loadDataFrompATH(final String mPath) {
data.clear();//data爲RecyclerView中要顯示的數據
new Thread() {
public void run() {
super.run();
File file = new File(mPath);
File[] listFiles = file.listFiles();//獲取子文件
for (File f : listFiles
) {
if (!f.isDirectory() || f.getName().startsWith(".")) {//如果不是路徑或者以 . 開頭的文件夾 則直接跳過
continue;
}
data.add(f.getAbsolutePath());//往集合中添加符合條件的數據
}
runOnUiThread(new Runnable() {
@Override
public void run() {
fileAdapter.setData(data);//將數據載入適配器當中
}
});
}
}.start();
}
重點來了
適配器FileAdapter的onBindViewHolder方法
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final String path = data.get(position);
boolean isChecked = false;//初始化一個boolean值 來判斷是否被選中
for (String s : selectData
) {//遍歷選中的集合
if (s.trim().equals(path)) {//如果集合中的子元素與適配其中的路徑相同
isChecked = true;//判斷已被選中
break;//終止循環
}
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {//設置checkBox的點擊事件
if (b) {//選中狀態
if (selectData.contains(path))//如果集合中包含了該元素則直接返回
return;
else//否則添加
selectData.add(path);
} else {//未選中狀態
if (selectData.contains(path))//如果集合中包含了該元素則移除
selectData.remove(path);
else//否則 返回
return;
}
}
});
holder.checkBox.setChecked(isChecked);
holder.tvFileDir.setText(path.substring(path.lastIndexOf("/") + 1));
holder.rootLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!holder.checkBox.isChecked()) //獲取checkBox的選中狀態來判斷是否能進入下一個文件夾
{
event.enterNextDir(data.get(position));//接口,用於在activity中回調
} else {
Toast.makeText(context, context.getString(R.string.filechoose_already), Toast.LENGTH_SHORT).show();
}
}
});
}
最後看看ativity中的回調方法
fileAdapter.setEvent(new FileAdapter.Event() {
@Override
public void enterNextDir(String path) {
editText.setText("");
mPath = path;//將子路徑賦值給當前路徑
loadDataFrompATH(mPath);//加載數據
}
});