有時候我們儲存檔案總會用到檔案瀏覽器功能.那麼今天博主帶大家做一個。
那麼開始,瀏覽檔案,我們就需要寫一個檔案工具類。
import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.util.Log; public class FileUtils { /** * 擷取目前的目錄下的所有檔案或檔案夾 * @param path 路徑 * @return */ public static List<Map<String,Object>> GetPathFilsList(String path) { List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); List<Map<String,Object>> filelist = new ArrayList<Map<String,Object>>(); try { String[] Files = new File(path).list(); for(String file : Files){ Map<String, Object> map = new HashMap<String, Object>(); if(new File(path+file).isDirectory()){ map.put("isDirectory",2); map.put("fileName", file); list.add(map); }else { map.put("isDirectory", 1); map.put("fileName", file); filelist.add(map); } } list.addAll(filelist); return list; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } }
這裡會將檔案和檔案夾區分出來,便於顯示區分。
之後我們需要用到一個適配器,用於顯示這些資料的ListView
private class FileBrowserAdapter extends BaseAdapter{ private List<Map<String, Object>> fileList; private Context context; public FileBrowserAdapter(Context Context, List<Map<String, Object>> fileList) { this.fileList = fileList; this.context = context; } @Override public int getCount() { return fileList == null ? 0 : fileList.size(); } @Override public Object getItem(int position) { return fileList.get(position); } @Override public long getItemId(int position) { return position; } @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = LayoutInflater .from(getApplicationContext()); View view = null; view = mInflater.inflate(R.layout.file_list_item, null); ImageView image = (ImageView) view .findViewById(R.id.file_list_item_image); if (Integer .parseInt(fileList.get(position).get("isDirectory") + "") == 2) image.setImageResource(R.drawable.folder); else if (Integer.parseInt(fileList.get(position).get("isDirectory") + "") == 1) image.setImageResource(R.drawable.documents); TextView textView = (TextView) view .findViewById(R.id.file_list_item_testview); textView.setTextColor(Color.BLACK); textView.setText(fileList.get(position).get("fileName") + ""); return view; } }
最後我們需要實現這些
dir = Environment.getExternalStorageDirectory() .getAbsolutePath() + "/"; fileListView = (ListView) findViewById(R.id.file_listview); listItemClickListener = new FileListItemClickListener(); // //設定點擊事件 fileListView.setOnItemClickListener(listItemClickListener); fileList = FileUtils.GetPathFilsList(dir); if (new File(dir).getParent() != null) { Map<String, Object> map = new HashMap<String, Object>(); map.put("isDirectory", 0); map.put("fileName", new File(dir).getParent()); fileList.add(0, map); } FileBrowserAdapter phoneFileBrowserAdapter = new FileBrowserAdapter( getApplicationContext(), fileList); fileListView.setAdapter(phoneFileBrowserAdapter);
效果圖:
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。