我想向我的应用程序添加图库片段或活动,以便可以显示下载的文件,例如图像和视频。
我目前正在出于以下目的使用此代码:
图库类:
class GalleryClass extends AsyncTask < Void, Void, Void > {
public static ArrayList < String > f = new ArrayList < > ();
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Gallery.gridView.setAdapter(new ImageAdapter(Gallery.context));
}
@Override
protected Void doInBackground(Void...voids) {
File dir = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("myFolder")));
File[] FileList = dir.listFiles();
if (FileList != null) {
for (File aFileList: FileList) {
f.add(aFileList.getAbsolutePath());
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
f.clear();
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ImageAdapter(Context context1) {
mContext = context1;
}
@Override
public int getCount() {
return f.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(230, 230));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
Glide.with(Gallery.context).load("file://" + f.get(position))
.apply(new RequestOptions()
.placeholder(R.drawable.)
.error(R.drawable.ic_error)
)
.into(imageView);
return imageView;
}
}
}
图库片段:
public Gallery() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_gallery, container, false);
gridView = view.findViewById(R.id.gv);
context = getActivity();
GalleryClass process = new GalleryClass();
process.execute();
return view;
}
}
上面的代码工作正常,并且正在从“ MyFolder”加载图像,但是MyFolder也包含子文件夹,并且它显示errorplaceholder而不是包含图像的子文件夹,我也想在同一视图中显示该子文件夹,并且当我单击该子文件夹时,它将显示该文件夹包含的图像。
我如何实现相同目标?
答案 0 :(得分:0)
这将列出包含png,jpg,mp4文件的所有文件夹和子文件夹。
String root_sd = Environment.getExternalStoragePublicDirectory("myFolder").toString();
File file = new File(root_sd);
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
File mFile = new File(file, list[i].getName());
File dirList[] = mFile.listFiles();
if(dirList == null) continue;
for (int j = 0; j < dirList.length; j++) {
if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".png")||dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".jpg")||dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp4")){
f.add(list[i].getName());
break;
}
}
}
答案 1 :(得分:0)
使用此:
File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
// is directory
}
}