簡介
Matisse是知乎開源的圖片選擇框架:https://github.com/zhihu/Matisse
中文文檔:https://blog.csdn.net/qiaoshi96_bk/article/details/76164913
使用:
1. 需要在項目setting.gradle 和 應用build.gradle中實現:
repositories {
jcenter()
}
implementation 'com.zhihu.android:matisse:0.5.3-beta3'
implementation 'com.github.bumptech.glide:glide:4.10.0'
2. 調出圖片選擇框
Matisse.from(UploadZoneActivity.this) //Activity .choose(MimeType.ofAll()) //選擇全部(包括視頻) .countable(true) // 有序選擇圖片 .maxSelectable(9) //最大選擇數量為9 .gridExpectedSize(400) //圖片顯示表格的大小 .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) .thumbnailScale(0.85f) //縮放比率 .theme(R.style.Matisse_Zhihu) //主題 暗色主題 R.style.Matisse_Dracula .imageEngine(new GlideEngine()) //加載方式 .forResult(REQUEST_CODE_CHOOSE); //結果返回碼 ,在onActivityResult中獲取
3. 獲取返回結果(URi)
private ArrayList<Uri> mSelected; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) { mSelected = (ArrayList<Uri>) Matisse.obtainResult(data); Log.d("Matisse", "mSelected: " + mSelected); } }
4. 通過Uri獲取真實地址
public static String getRealFilePath(final Context context, final Uri uri ) { if ( null == uri ) return null; final String scheme = uri.getScheme(); String data = null; if ( scheme == null ) data = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { data = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA ); if ( index > -1 ) { data = cursor.getString( index ); } } cursor.close(); } } return data; }
注意:
1. 對於Android10需要加
android:requestLegacyExternalStorage="true"
2. 需要使用Matisse 時,OnActivityResult()方法,需要判斷 resultCode == RESULT_OK 來保證有值