歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android從圖庫(Gallery)選擇一張圖片

Android從圖庫(Gallery)選擇一張圖片

日期:2017/3/1 9:50:24   编辑:Linux編程

在Android編程中,有時我們可能會有這樣的需求,從圖庫裡選擇一張圖片作為頭像

這時,我們就需要從我們的應用中去激活系統的圖庫應用,並選擇一張圖片

這個接口Android已經為我們提供

我們先來看一下android圖庫的系統源碼,打開android源碼_home\packages\apps,在裡邊我們找到gallery文件夾,即為圖庫的源碼

打開後,我們先打開清單文件,在裡邊找到這樣一段代碼

<activity android:name="com.android.camera.ImageGallery"
android:label="@string/gallery_label"
android:configChanges="orientation|keyboardHidden"
android:icon="@drawable/ic_launcher_gallery">
.......
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
.......

</activity>

從上邊的意圖過濾器我們可以發現,我們可以通過一個叫android.intent.action.PICK的action來激活圖庫並選擇圖片或是視頻

為了知道圖庫應用給我們返回的key值是什麼,我們還需到com.android.camera.ImageGallery類去看一下源碼

在src目錄下找到該類並打開,我們在裡邊搜“setResult”關鍵字,我們發現這樣一段代碼

else {
Intent result = new Intent(null, img.fullSizeImageUri());
if (myExtras != null && myExtras.getBoolean("return-data")) {
// The size of a transaction should be below 100K.
Bitmap bitmap = img.fullSizeBitmap(
IImage.UNCONSTRAINED, 100 * 1024);
if (bitmap != null) {
result.putExtra("data", bitmap);
}
}
setResult(RESULT_OK, result);
finish();

 

Copyright © Linux教程網 All Rights Reserved