編輯:Android 開發教學
給定一個資料夾路徑,列出裡面所有圖片檔案(png、gif、jpg、jpeg)的相關資訊:檔名、大小、建立時間與絕對路徑,並在列表中顯示縮圖。

public class Util {
/** 計算檔案大小,自動換算成 B / KB / MB */
public static String ShowLongFileSzie(Long length) {
if (length >= 1048576) {
return (length / 1048576) + "MB";
} else if (length >= 1024) {
return (length / 1024) + "KB";
} else if (length < 1024) {
return length + "B";
} else {
return "0KB";
}
}
/** 取得指定路徑下的全部圖片資訊 */
public static List<AddFileInfo> getSDPathFrom() {
List<AddFileInfo> imagePathList = new ArrayList<AddFileInfo>();
// 目標資料夾路徑
String filePath = Environment.getExternalStorageDirectory().toString()
+ File.separator + "BigNoxHD/cache/";
File fileAll = new File(filePath);
File[] files = fileAll.listFiles();
// 逐一檢查並過濾出圖片格式
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (checkIsFile(file.getPath())) {
String time = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(file.lastModified()));
AddFileInfo info = new AddFileInfo(file.getName(),
Util.ShowLongFileSzie(file.length()), time, file.getAbsolutePath());
imagePathList.add(info);
}
}
return imagePathList;
}
/** 驗證副檔名是否為圖片 */
public static boolean checkIsFile(String fName) {
boolean isImageFile = false;
String FileEnd = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
if (FileEnd.equals("jpg") || FileEnd.equals("png")
|| FileEnd.equals("gif") || FileEnd.equals("jpeg")) {
isImageFile = true;
}
return isImageFile;
}
/**
* 依路徑載入並縮放圖片,避免大圖直接進記憶體造成 OOM
* @param path 檔案路徑
* @param w 目標寬
* @param h 目標高
*/
public static Bitmap convertToBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 第一次只讀取尺寸,不真正配置像素記憶體
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
}
這裡有個關鍵技巧值得單獨說明:inJustDecodeBounds = true 時,decodeFile 只讀取圖片的寬高而不配置像素記憶體。先用它量出原圖尺寸、算出 inSampleSize,再正式解碼,就能大幅降低大圖造成 OOM 的風險。
public class MainActivity extends Activity {
private ListView mListview;
private List<AddFileInfo> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mListview = (ListView) findViewById(R.id.listview);
list = Util.getSDPathFrom();
mListview.setAdapter(new Adapter(MainActivity.this));
}
class Adapter extends BaseAdapter {
private LayoutInflater inflater;
private Context context;
public Adapter(Context context) {
this.context = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (null == convertView) {
convertView = inflater.inflate(R.layout.item_mytask_file_listview, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
AddFileInfo info = (AddFileInfo) getItem(position);
holder.img.setImageBitmap(Util.convertToBitmap(info.getPath(), 99, 99));
holder.tv_name.setText("文件名稱:" + info.getName());
holder.size.setText("文件大小:" + info.getSize());
holder.time.setText("文件創建時間:" + info.getTime());
return convertView;
}
}
class ViewHolder {
private TextView tv_name;
private TextView size;
private TextView time;
private ImageView img;
public ViewHolder(View view) {
img = (ImageView) view.findViewById(R.id.img);
tv_name = (TextView) view.findViewById(R.id.item_file_name);
size = (TextView) view.findViewById(R.id.item_file_size);
time = (TextView) view.findViewById(R.id.item_file_time);
}
}
}
Adapter 裡用的是標準的 ViewHolder 模式:convertView 為 null 時才 inflate 並把 holder 掛上 tag,複用時直接取回,避免每捲動一次就重複 findViewById。
<!-- SD卡權限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
在 Android 6.0 以上,WRITE_EXTERNAL_STORAGE 還必須另外向使用者動態申請,否則讀不到路徑下的檔案。
Android 開發入門:Activity 生命週期
Activity 是 Android 應用程式的核心元件,透過一組回呼方法控制其生命週期。常見回呼包括 onCreate、onStart、onResume、onPause
Android SearchView 實用細節整理:預設展開、自訂樣式與搜尋下拉提示
以下內容全部以 android.support.v7.widget.SearchView 為對象。相比平台上原生的 SearchView,v7 版本提供了多得多可調_co
Android 開發入門:顯示等待對話框
在登入、載入資料或執行計算時,常會顯示「請稍候」對話框。Android 可使用 ProgressDialog.show 建立等待提示。由於對話框為模態,會遮蓋其他 UI,
用 BroadcastReceiver 監聽來電並記錄通話狀態
BroadcastReceiver 是 Android 四大元件之一,可監聽系統廣播。若要常駐監聽來電,可監聽開機完成廣播,啟動背景 Service,再由 Telepho