編輯:關於 Android 程式設計
從圖庫挑一張圖顯示在自己的界面上,是很基礎也很常被問到的需求。實現起來其實不麻煩,三步就能搞定。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="wrap_content">
</ImageView>
<Button
android:layout_height="wrap_content"
android:text="Load Picture"
android:layout_width="wrap_content"
android:id="@+id/buttonLoadPicture"
android:layout_weight="0"
android:layout_gravity="center">
</Button>
</LinearLayout>
本質上就是一個隱式 Intent:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
關鍵是這一句:Uri selectedImage = data.getData(); 它拿到了用戶選中圖片的 Uri。後續通過 ContentResolver 查詢 MediaStore,從 DATA 列取出真實路徑,再交給 BitmapFactory 解碼顯示。
實務上要注意兩點:一是 Android 6.0 以上讀取外部媒體需要 READ_EXTERNAL_STORAGE 運行時權限;二是大圖直接 decodeFile 容易 OOM,建議按 inSampleSize 降採樣,或者改用 Glide、Coil 這類圖片庫加載。
感謝閱讀,希望能幫助到大家。
使用 CountDownTimer 實作搶購與簡訊驗證碼倒數
常見倒數做法 Android 中實作倒數的方式很多,例如 Timer、Handler、Thread 或 Runnable。這些方式都能完成倒數,但若要處理「剩餘時間更新」
BlueStacks 安卓模擬器簡單設定使用圖解教學
BlueStacks 是一套讓 Android 應用能跑在電腦上的模擬器(現已支援 Windows 與 Mac),裝好之後就能在電腦上玩手遊。它的操作邏輯很直觀,很快就能
Ionic2 打造 App 啟動時的左右滑動歡迎頁
幾乎每一個質感在線的 App,第一次啟動時都會有一組歡迎畫面:通常是數個單頁,滑到最後一頁才出現「開始使用」的按鈕。本文用 Ionic2 一步步實作這個效果,其實非常簡單
OkHttp 源碼解析:請求流程、攔截器、連接池與重連機制
OkHttp 是 Android 與 Java 應用中常見的 HTTP 客戶端。它支援 SPDY、連接池、GZIP、快取與自動重連,並提供近似 HttpURLConnec