├── .gitignore ├── .idea ├── assetWizardSettings.xml ├── caches │ └── build_file_checksums.ser ├── codeStyles │ └── Project.xml ├── gradle.xml ├── misc.xml └── runConfigurations.xml ├── LICENSE ├── PhotoSelector ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── winfo │ │ └── photoselector │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── winfo │ │ │ └── photoselector │ │ │ ├── ImageSelectorActivity.java │ │ │ ├── PhotoSelector.java │ │ │ ├── PreviewActivity.java │ │ │ ├── RvPreviewActivity.java │ │ │ ├── adapter │ │ │ ├── BottomPreviewAdapter.java │ │ │ ├── FolderAdapter.java │ │ │ ├── ImageAdapter.java │ │ │ ├── ImagePagerAdapter.java │ │ │ └── PreviewImageAdapter.java │ │ │ ├── entity │ │ │ ├── Folder.java │ │ │ └── Image.java │ │ │ ├── model │ │ │ └── ImageModel.java │ │ │ ├── utils │ │ │ ├── DateUtils.java │ │ │ ├── ImageCaptureManager.java │ │ │ ├── ImageUtil.java │ │ │ ├── PermissionsConstant.java │ │ │ ├── PermissionsUtils.java │ │ │ ├── StatusBarUtils.java │ │ │ └── StringUtils.java │ │ │ └── widget │ │ │ ├── AnimatorUtil.java │ │ │ ├── MyViewPager.java │ │ │ ├── ScaleDownShowBehavior.java │ │ │ └── SquareImageView.java │ └── res │ │ ├── anim │ │ └── glide_anim.xml │ │ ├── color │ │ └── text_color.xml │ │ ├── drawable-xhdpi │ │ └── text_indicator.png │ │ ├── drawable │ │ ├── border.9.png │ │ ├── btn_back_selector.xml │ │ ├── btn_foreground_selector.xml │ │ ├── btn_green_shape.xml │ │ ├── camera.xml │ │ ├── folder_bg.xml │ │ ├── ic_image.xml │ │ ├── ic_image_select.xml │ │ ├── ic_image_un_select.xml │ │ ├── ic_img_load_fail.xml │ │ ├── take_photo_normal.xml │ │ ├── take_photo_press.xml │ │ └── toolbar_back.xml │ │ ├── layout │ │ ├── activity_image_select.xml │ │ ├── activity_image_select2.xml │ │ ├── activity_preview.xml │ │ ├── activity_rv_preview.xml │ │ ├── adapter_camera_item.xml │ │ ├── adapter_folder.xml │ │ ├── adapter_images_item.xml │ │ ├── bootm_preview_item.xml │ │ ├── bsd_folder_dialog.xml │ │ ├── item_view_pager.xml │ │ └── preview_item.xml │ │ └── values │ │ ├── color.xml │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── winfo │ └── photoselector │ └── ExampleUnitTest.java ├── README.md ├── apk └── PhotoSelector.apk ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── winfo │ │ └── photoselectordemo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── winfo │ │ │ └── photoselectordemo │ │ │ ├── ImageAdapter.java │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ └── adapter_image.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── winfo │ └── photoselectordemo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images ├── clip.jpg ├── folder.jpg ├── preview.jpg ├── preview_list.jpg └── selector.jpg └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/libraries 5 | /.idea/modules.xml 6 | /.idea/workspace.xml 7 | .DS_Store 8 | /build 9 | /captures 10 | .externalNativeBuild 11 | -------------------------------------------------------------------------------- /.idea/assetWizardSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 31 | 32 | -------------------------------------------------------------------------------- /.idea/caches/build_file_checksums.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wj576038874/PhotoSelector/2d5d258ee0e7231b919deed3fd58074dc409c691/.idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 27 | 28 | 29 | 30 | 31 | 32 | 34 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PhotoSelector/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /PhotoSelector/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.novoda.bintray-release'//添加 3 | 4 | android { 5 | compileSdkVersion 27 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 27 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | 22 | } 23 | 24 | dependencies { 25 | implementation fileTree(dir: 'libs', include: ['*.jar']) 26 | implementation 'com.android.support:appcompat-v7:27.1.1' 27 | testImplementation 'junit:junit:4.12' 28 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 29 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 30 | api 'com.android.support:recyclerview-v7:27.1.1' 31 | api 'com.github.bumptech.glide:glide:4.7.1' 32 | api 'com.github.chrisbanes:PhotoView:2.1.3' 33 | // annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1' 34 | api 'com.github.yalantis:ucrop:2.2.2' 35 | api 'com.android.support:design:27.1.1' 36 | } 37 | //添加 38 | publish { 39 | // repoName = 'ImageSelector'//不指明,默认是上传到maven 40 | userOrg = 'wenjie940409'//bintray.com你的用户名 41 | groupId = 'com.winfo.photoselector'//jcenter上的路径 42 | artifactId = 'PhotoSelector'//项目名称 43 | publishVersion = '1.2.1'//版本号 44 | desc = 'PhotoSelector'//描述,不重要 45 | website = 'https://github.com/wj576038874'//网站,不重要;尽量模拟github上的地址,例如我这样的;当然你有地址最好了 46 | } 47 | -------------------------------------------------------------------------------- /PhotoSelector/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /PhotoSelector/src/androidTest/java/com/winfo/photoselector/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.winfo.photoselector.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 10 | 11 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/PhotoSelector.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.support.annotation.ColorInt; 9 | import android.support.annotation.NonNull; 10 | import com.winfo.photoselector.utils.PermissionsUtils; 11 | import com.yalantis.ucrop.UCrop; 12 | import java.util.ArrayList; 13 | 14 | public class PhotoSelector { 15 | 16 | 17 | public static final int CROP_RECTANG = 1; 18 | public static final int CROP_CIRCLE = 2; 19 | 20 | /** 21 | * 默认最大选择数 22 | */ 23 | public static final int DEFAULT_MAX_SELECTED_COUNT = 9; 24 | 25 | /** 26 | * 默认显示的列数 27 | */ 28 | public static final int DEFAULT_GRID_COLUMN = 3; 29 | 30 | /** 31 | * 默认的requesrCode 32 | */ 33 | public static final int DEFAULT_REQUEST_CODE = 999; 34 | 35 | 36 | public static final int RESULT_CODE = 1000; 37 | 38 | /** 39 | * 拍照裁剪 40 | */ 41 | public static final int TAKE_PHOTO_CROP_REQUESTCODE = 1001; 42 | 43 | /** 44 | * 拍照 不裁剪 45 | */ 46 | public static final int TAKE_PHOTO_REQUESTCODE = 1002; 47 | 48 | public static final int CROP_REQUESTCODE = 1003; 49 | 50 | /** 51 | * 图片选择的结果 52 | */ 53 | public static final String SELECT_RESULT = "select_result"; 54 | 55 | /** 56 | * 图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。 57 | */ 58 | public static final String EXTRA_MAX_SELECTED_COUNT = "max_selected_count"; 59 | 60 | /** 61 | * 显示列数 62 | */ 63 | public static final String EXTRA_GRID_COLUMN = "column"; 64 | 65 | /** 66 | * 是否显示拍照 67 | */ 68 | public static final String EXTRA_SHOW_CAMERA = "show_camera"; 69 | 70 | /** 71 | * 已经选择的照片集合 72 | */ 73 | public static final String EXTRA_SELECTED_IMAGES = "selected_images"; 74 | 75 | /** 76 | * 是否单选 77 | */ 78 | public static final String EXTRA_SINGLE = "single"; 79 | 80 | /** 81 | * 是否裁剪 82 | */ 83 | public static final String EXTRA_CROP = "is_crop"; 84 | 85 | public static final String EXTRA_CROP_MODE = "crop_mode"; 86 | 87 | /** 88 | * toolbar和bottombar是否为material design风格 89 | */ 90 | public static final String EXTRA_MATERIAL_DESIGN = "material_design"; 91 | 92 | 93 | /** 94 | * toolBar的颜色值 95 | */ 96 | public static final String EXTRA_TOOLBARCOLOR = "toolBarColor"; 97 | 98 | /** 99 | * bottomBar的颜色值 100 | */ 101 | public static final String EXTRA_BOTTOMBARCOLOR = "bottomBarColor"; 102 | 103 | /** 104 | * 状态栏的颜色值 105 | */ 106 | public static final String EXTRA_STATUSBARCOLOR = "statusBarColor"; 107 | 108 | /** 109 | * 初始位置 110 | */ 111 | public static final String EXTRA_POSITION = "position"; 112 | 113 | /** 114 | * true是点击预览按钮进入到的预览界面 115 | * false是点击item进入到的预览界面 116 | */ 117 | public static final String EXTRA_ISPREVIEW = "isPreview"; 118 | 119 | 120 | public static final String IS_CONFIRM = "is_confirm"; 121 | 122 | 123 | /** 124 | * 获取裁剪之后的图片的uri 125 | * 126 | * @param intent data 127 | * @return uri 128 | */ 129 | public static Uri getCropImageUri(@NonNull Intent intent) { 130 | return UCrop.getOutput(intent); 131 | } 132 | 133 | 134 | public static PhotoSelectorBuilder builder() { 135 | return new PhotoSelectorBuilder(); 136 | } 137 | 138 | public static class PhotoSelectorBuilder { 139 | private Bundle mPickerOptionsBundle; 140 | private Intent mPickerIntent; 141 | 142 | PhotoSelectorBuilder() { 143 | mPickerOptionsBundle = new Bundle(); 144 | mPickerIntent = new Intent(); 145 | } 146 | 147 | /** 148 | * Send the Intent from an Activity with a custom request code 149 | * 150 | * @param activity Activity to receive result 151 | * @param requestCode requestCode for result 152 | */ 153 | public void start(@NonNull Activity activity, int requestCode) { 154 | if (PermissionsUtils.checkReadStoragePermission(activity)) { 155 | activity.startActivityForResult(getIntent(activity), requestCode); 156 | } 157 | } 158 | 159 | /** 160 | * Get Intent to start {@link ImageSelectorActivity} 161 | * 162 | * @return Intent for {@link ImageSelectorActivity} 163 | */ 164 | private Intent getIntent(@NonNull Context context) { 165 | mPickerIntent.setClass(context, ImageSelectorActivity.class); 166 | mPickerIntent.putExtras(mPickerOptionsBundle); 167 | return mPickerIntent; 168 | } 169 | 170 | /** 171 | * @param activity Activity to receive result 172 | */ 173 | public void start(@NonNull Activity activity) { 174 | start(activity, DEFAULT_REQUEST_CODE); 175 | } 176 | 177 | /** 178 | * 设置最大选择数量 179 | * 180 | * @param maxSelectCount 数量 181 | * @return PhotoSelectorBuilder 182 | */ 183 | public PhotoSelectorBuilder setMaxSelectCount(int maxSelectCount) { 184 | mPickerOptionsBundle.putInt(EXTRA_MAX_SELECTED_COUNT, maxSelectCount); 185 | return this; 186 | } 187 | 188 | /** 189 | * 是否是单选 190 | * 191 | * @param isSingle 是否是单选 192 | * @return PhotoSelectorBuilder 193 | */ 194 | public PhotoSelectorBuilder setSingle(boolean isSingle) { 195 | mPickerOptionsBundle.putBoolean(EXTRA_SINGLE, isSingle); 196 | return this; 197 | } 198 | 199 | /** 200 | * 设置列数 201 | * 202 | * @param columnCount 列数 203 | * @return PhotoSelectorBuilder 204 | */ 205 | public PhotoSelectorBuilder setGridColumnCount(int columnCount) { 206 | mPickerOptionsBundle.putInt(EXTRA_GRID_COLUMN, columnCount); 207 | return this; 208 | } 209 | 210 | /** 211 | * 是否显示拍照 212 | * 213 | * @param showCamera 是否显示拍照 214 | * @return PhotoSelectorBuilder 215 | */ 216 | public PhotoSelectorBuilder setShowCamera(boolean showCamera) { 217 | mPickerOptionsBundle.putBoolean(EXTRA_SHOW_CAMERA, showCamera); 218 | return this; 219 | } 220 | 221 | /** 222 | * 已经选择的照片集合 223 | * 224 | * @param selected 已经选择的照片集合 225 | * @return PhotoSelectorBuilder 226 | */ 227 | public PhotoSelectorBuilder setSelected(ArrayList selected) { 228 | mPickerOptionsBundle.putStringArrayList(EXTRA_SELECTED_IMAGES, selected); 229 | return this; 230 | } 231 | 232 | /** 233 | * toolBar的颜色 234 | * 235 | * @param toolBarColor toolBar的颜色 236 | * @return PhotoSelectorBuilder 237 | */ 238 | public PhotoSelectorBuilder setToolBarColor(@ColorInt int toolBarColor) { 239 | mPickerOptionsBundle.putInt(EXTRA_TOOLBARCOLOR, toolBarColor); 240 | return this; 241 | } 242 | 243 | /** 244 | * bottomBar的颜色 245 | * 246 | * @param bottomBarColor bottomBar的颜色 247 | * @return PhotoSelectorBuilder 248 | */ 249 | public PhotoSelectorBuilder setBottomBarColor(@ColorInt int bottomBarColor) { 250 | mPickerOptionsBundle.putInt(EXTRA_BOTTOMBARCOLOR, bottomBarColor); 251 | return this; 252 | } 253 | 254 | /** 255 | * 状态栏的颜色 256 | * 257 | * @param statusBarColor 状态栏的颜色 258 | * @return PhotoSelectorBuilder 259 | */ 260 | public PhotoSelectorBuilder setStatusBarColor(@ColorInt int statusBarColor) { 261 | mPickerOptionsBundle.putInt(EXTRA_STATUSBARCOLOR, statusBarColor); 262 | return this; 263 | } 264 | 265 | /** 266 | * oolbar和bototmbar是否显示materialDesign风格 267 | * 268 | * @param materialDesign toolbar和bototmbar是否显示materialDesign风格 269 | * @return PhotoSelectorBuilder 270 | */ 271 | public PhotoSelectorBuilder setMaterialDesign(boolean materialDesign) { 272 | mPickerOptionsBundle.putBoolean(EXTRA_MATERIAL_DESIGN, materialDesign); 273 | return this; 274 | } 275 | 276 | /** 277 | * 是否裁剪,剪切,修剪 278 | * 279 | * @return PhotoSelectorBuilder 280 | */ 281 | public PhotoSelectorBuilder setCrop(boolean isCrop) { 282 | mPickerOptionsBundle.putBoolean(EXTRA_CROP, isCrop); 283 | return this; 284 | } 285 | 286 | /** 287 | * 设置裁剪的样式 288 | * 289 | * @param mode 圆形 矩形 290 | * @return PhotoSelectorBuilder 291 | */ 292 | public PhotoSelectorBuilder setCropMode(int mode) { 293 | mPickerOptionsBundle.putInt(EXTRA_CROP_MODE, mode); 294 | return this; 295 | } 296 | 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/PreviewActivity.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector; 2 | 3 | import android.animation.Animator; 4 | import android.animation.AnimatorListenerAdapter; 5 | import android.animation.ObjectAnimator; 6 | import android.annotation.SuppressLint; 7 | import android.app.Activity; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.content.res.Resources; 11 | import android.graphics.Bitmap; 12 | import android.graphics.BitmapFactory; 13 | import android.graphics.drawable.BitmapDrawable; 14 | import android.os.Build; 15 | import android.os.Bundle; 16 | import android.support.annotation.Nullable; 17 | import android.support.annotation.RequiresApi; 18 | import android.support.v4.content.ContextCompat; 19 | import android.support.v4.view.ViewPager; 20 | import android.support.v7.app.AppCompatActivity; 21 | import android.view.View; 22 | import android.view.Window; 23 | import android.view.WindowManager; 24 | import android.widget.FrameLayout; 25 | import android.widget.RelativeLayout; 26 | import android.widget.TextView; 27 | 28 | import com.winfo.photoselector.adapter.ImagePagerAdapter; 29 | import com.winfo.photoselector.entity.Image; 30 | import com.winfo.photoselector.widget.MyViewPager; 31 | 32 | import java.util.ArrayList; 33 | 34 | import static android.animation.ObjectAnimator.ofFloat; 35 | 36 | public class PreviewActivity extends AppCompatActivity { 37 | 38 | private MyViewPager vpImage; 39 | private TextView tvIndicator; 40 | private TextView tvConfirm; 41 | private FrameLayout btnConfirm; 42 | private TextView tvSelect; 43 | private RelativeLayout rlTopBar; 44 | private RelativeLayout rlBottomBar; 45 | 46 | //tempImages和tempSelectImages用于图片列表数据的页面传输。 47 | //之所以不要Intent传输这两个图片列表,因为要保证两位页面操作的是同一个列表数据,同时可以避免数据量大时, 48 | // 用Intent传输发生的错误问题。 49 | private static ArrayList tempImages; 50 | private static ArrayList tempSelectImages; 51 | 52 | private ArrayList mImages; 53 | private ArrayList mSelectImages; 54 | private boolean isShowBar = true; 55 | private boolean isConfirm = false; 56 | private boolean isSingle; 57 | private int mMaxCount; 58 | 59 | private BitmapDrawable mSelectDrawable; 60 | private BitmapDrawable mUnSelectDrawable; 61 | 62 | public static void openActivity(Activity activity, ArrayList images, 63 | ArrayList selectImages, boolean isSingle, 64 | int maxSelectCount, int position, int topBarColor, int bottomBarColor, int statusBarColor) { 65 | tempImages = images; 66 | tempSelectImages = selectImages; 67 | Intent intent = new Intent(activity, PreviewActivity.class); 68 | intent.putExtra(PhotoSelector.EXTRA_MAX_SELECTED_COUNT, maxSelectCount); 69 | intent.putExtra(PhotoSelector.EXTRA_SINGLE, isSingle); 70 | intent.putExtra(PhotoSelector.EXTRA_POSITION, position); 71 | intent.putExtra(PhotoSelector.EXTRA_TOOLBARCOLOR, topBarColor); 72 | intent.putExtra(PhotoSelector.EXTRA_BOTTOMBARCOLOR, bottomBarColor); 73 | intent.putExtra(PhotoSelector.EXTRA_STATUSBARCOLOR, statusBarColor); 74 | activity.startActivityForResult(intent, PhotoSelector.RESULT_CODE); 75 | } 76 | 77 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 78 | @SuppressLint("SetTextI18n") 79 | @Override 80 | protected void onCreate(@Nullable Bundle savedInstanceState) { 81 | super.onCreate(savedInstanceState); 82 | setContentView(R.layout.activity_preview); 83 | 84 | setStatusBarVisible(true); 85 | mImages = tempImages; 86 | tempImages = null; 87 | mSelectImages = tempSelectImages; 88 | tempSelectImages = null; 89 | 90 | Intent intent = getIntent(); 91 | mMaxCount = intent.getIntExtra(PhotoSelector.EXTRA_MAX_SELECTED_COUNT, 0); 92 | isSingle = intent.getBooleanExtra(PhotoSelector.EXTRA_SINGLE, false); 93 | 94 | Resources resources = getResources(); 95 | Bitmap selectBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_image_select); 96 | mSelectDrawable = new BitmapDrawable(resources, selectBitmap); 97 | mSelectDrawable.setBounds(0, 0, selectBitmap.getWidth(), selectBitmap.getHeight()); 98 | 99 | Bitmap unSelectBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_image_un_select); 100 | mUnSelectDrawable = new BitmapDrawable(resources, unSelectBitmap); 101 | mUnSelectDrawable.setBounds(0, 0, unSelectBitmap.getWidth(), unSelectBitmap.getHeight()); 102 | 103 | setStatusBarColor(intent.getIntExtra(PhotoSelector.EXTRA_STATUSBARCOLOR, R.color.blue)); 104 | initView(); 105 | setToolBarColor(intent.getIntExtra(PhotoSelector.EXTRA_TOOLBARCOLOR, R.color.blue)); 106 | setBottomBarColor(intent.getIntExtra(PhotoSelector.EXTRA_BOTTOMBARCOLOR, R.color.blue)); 107 | initListener(); 108 | initViewPager(); 109 | 110 | tvIndicator.setText(1 + "/" + mImages.size()); 111 | changeSelect(mImages.get(0)); 112 | vpImage.setCurrentItem(intent.getIntExtra(PhotoSelector.EXTRA_POSITION, 0)); 113 | } 114 | 115 | private void initView() { 116 | vpImage = findViewById(R.id.vp_image); 117 | tvIndicator = findViewById(R.id.tv_indicator); 118 | tvConfirm = findViewById(R.id.tv_confirm); 119 | btnConfirm = findViewById(R.id.btn_confirm); 120 | tvSelect = findViewById(R.id.tv_select); 121 | rlTopBar = findViewById(R.id.rl_top_bar); 122 | rlBottomBar = findViewById(R.id.rl_bottom_bar); 123 | 124 | RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) rlTopBar.getLayoutParams(); 125 | lp.topMargin = getStatusBarHeight(this); 126 | rlTopBar.setLayoutParams(lp); 127 | } 128 | 129 | private void initListener() { 130 | findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() { 131 | @Override 132 | public void onClick(View v) { 133 | finish(); 134 | } 135 | }); 136 | btnConfirm.setOnClickListener(new View.OnClickListener() { 137 | @Override 138 | public void onClick(View v) { 139 | isConfirm = true; 140 | finish(); 141 | } 142 | }); 143 | tvSelect.setOnClickListener(new View.OnClickListener() { 144 | @Override 145 | public void onClick(View v) { 146 | clickSelect(); 147 | } 148 | }); 149 | } 150 | 151 | /** 152 | * 初始化ViewPager 153 | */ 154 | private void initViewPager() { 155 | ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages); 156 | vpImage.setAdapter(adapter); 157 | adapter.setOnItemClickListener(new ImagePagerAdapter.OnItemClickListener() { 158 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 159 | @Override 160 | public void onItemClick(int position, Image image) { 161 | if (isShowBar) { 162 | hideBar(); 163 | } else { 164 | showBar(); 165 | } 166 | } 167 | }); 168 | vpImage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 169 | @Override 170 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 171 | } 172 | 173 | @SuppressLint("SetTextI18n") 174 | @Override 175 | public void onPageSelected(int position) { 176 | tvIndicator.setText(position + 1 + "/" + mImages.size()); 177 | changeSelect(mImages.get(position)); 178 | } 179 | 180 | @Override 181 | public void onPageScrollStateChanged(int state) { 182 | } 183 | }); 184 | 185 | } 186 | 187 | /** 188 | * 修改状态栏颜色 189 | * 190 | * @param statusBarColor 颜色值 191 | */ 192 | private void setStatusBarColor(int statusBarColor) { 193 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 194 | Window window = getWindow(); 195 | window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 196 | window.setStatusBarColor(ContextCompat.getColor(this, statusBarColor)); 197 | } 198 | } 199 | 200 | /** 201 | * 修改topbar的颜色 202 | * 203 | * @param color 颜色值 204 | */ 205 | private void setToolBarColor(int color) { 206 | rlTopBar.setBackgroundColor(ContextCompat.getColor(this, color)); 207 | } 208 | 209 | /** 210 | * 修改bottombar的颜色 211 | * 212 | * @param color 颜色值 213 | */ 214 | private void setBottomBarColor(int color) { 215 | rlBottomBar.setBackgroundColor(ContextCompat.getColor(this, color)); 216 | } 217 | 218 | 219 | /** 220 | * 获取状态栏高度 221 | */ 222 | public static int getStatusBarHeight(Context context) { 223 | int result = 0; 224 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); 225 | if (resourceId > 0) { 226 | result = context.getResources().getDimensionPixelSize(resourceId); 227 | } 228 | return result; 229 | } 230 | 231 | /** 232 | * 显示和隐藏状态栏 233 | * 234 | * @param show 是否显示 235 | */ 236 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 237 | private void setStatusBarVisible(boolean show) { 238 | if (show) { 239 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 240 | } else { 241 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 242 | | View.SYSTEM_UI_FLAG_FULLSCREEN); 243 | } 244 | } 245 | 246 | /** 247 | * 显示头部和尾部栏 248 | */ 249 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 250 | private void showBar() { 251 | isShowBar = true; 252 | setStatusBarVisible(true); 253 | //添加延时,保证StatusBar完全显示后再进行动画。 254 | rlTopBar.postDelayed(new Runnable() { 255 | @Override 256 | public void run() { 257 | if (rlTopBar != null) { 258 | ObjectAnimator animator = ofFloat(rlTopBar, "translationY", 259 | rlTopBar.getTranslationY(), 0).setDuration(300); 260 | animator.addListener(new AnimatorListenerAdapter() { 261 | @Override 262 | public void onAnimationStart(Animator animation) { 263 | super.onAnimationStart(animation); 264 | if (rlTopBar != null) { 265 | rlTopBar.setVisibility(View.VISIBLE); 266 | } 267 | } 268 | }); 269 | animator.start(); 270 | ofFloat(rlBottomBar, "translationY", rlBottomBar.getTranslationY(), 0) 271 | .setDuration(300).start(); 272 | } 273 | } 274 | }, 100); 275 | } 276 | 277 | /** 278 | * 隐藏头部和尾部栏 279 | */ 280 | private void hideBar() { 281 | isShowBar = false; 282 | ObjectAnimator animator = ObjectAnimator.ofFloat(rlTopBar, "translationY", 283 | 0, -rlTopBar.getHeight()).setDuration(300); 284 | animator.addListener(new AnimatorListenerAdapter() { 285 | @Override 286 | public void onAnimationEnd(Animator animation) { 287 | super.onAnimationEnd(animation); 288 | if (rlTopBar != null) { 289 | rlTopBar.setVisibility(View.GONE); 290 | //添加延时,保证rlTopBar完全隐藏后再隐藏StatusBar。 291 | rlTopBar.postDelayed(new Runnable() { 292 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 293 | @Override 294 | public void run() { 295 | setStatusBarVisible(false); 296 | } 297 | }, 5); 298 | } 299 | } 300 | }); 301 | animator.start(); 302 | ofFloat(rlBottomBar, "translationY", 0, rlBottomBar.getHeight()) 303 | .setDuration(300).start(); 304 | } 305 | 306 | private void clickSelect() { 307 | int position = vpImage.getCurrentItem(); 308 | if (mImages != null && mImages.size() > position) { 309 | Image image = mImages.get(position); 310 | if (mSelectImages.contains(image)) { 311 | mSelectImages.remove(image); 312 | } else if (isSingle) { 313 | mSelectImages.clear(); 314 | mSelectImages.add(image); 315 | } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) { 316 | mSelectImages.add(image); 317 | } 318 | changeSelect(image); 319 | } 320 | } 321 | 322 | private void changeSelect(Image image) { 323 | tvSelect.setCompoundDrawables(mSelectImages.contains(image) ? 324 | mSelectDrawable : mUnSelectDrawable, null, null, null); 325 | setSelectImageCount(mSelectImages.size()); 326 | } 327 | 328 | @SuppressLint("SetTextI18n") 329 | private void setSelectImageCount(int count) { 330 | if (count == 0) { 331 | btnConfirm.setEnabled(false); 332 | tvConfirm.setText("确定"); 333 | } else { 334 | btnConfirm.setEnabled(true); 335 | if (isSingle) { 336 | tvConfirm.setText("确定"); 337 | } else if (mMaxCount > 0) { 338 | tvConfirm.setText("确定(" + count + "/" + mMaxCount + ")"); 339 | } else { 340 | tvConfirm.setText("确定(" + count + ")"); 341 | } 342 | } 343 | } 344 | 345 | @Override 346 | public void finish() { 347 | //Activity关闭时,通过Intent把用户的操作(确定/返回)传给ImageSelectActivity。 348 | Intent intent = new Intent(); 349 | intent.putExtra(PhotoSelector.IS_CONFIRM, isConfirm); 350 | setResult(PhotoSelector.RESULT_CODE, intent); 351 | super.finish(); 352 | } 353 | } 354 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/RvPreviewActivity.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector; 2 | 3 | import android.animation.Animator; 4 | import android.animation.AnimatorListenerAdapter; 5 | import android.animation.ObjectAnimator; 6 | import android.annotation.SuppressLint; 7 | import android.app.Activity; 8 | import android.content.Intent; 9 | import android.content.res.Resources; 10 | import android.graphics.Bitmap; 11 | import android.graphics.drawable.BitmapDrawable; 12 | import android.os.Build; 13 | import android.os.Bundle; 14 | import android.support.annotation.ColorInt; 15 | import android.support.annotation.Nullable; 16 | import android.support.annotation.RequiresApi; 17 | import android.support.design.widget.AppBarLayout; 18 | import android.support.v4.content.ContextCompat; 19 | import android.support.v7.app.ActionBar; 20 | import android.support.v7.app.AppCompatActivity; 21 | import android.support.v7.widget.LinearLayoutManager; 22 | import android.support.v7.widget.PagerSnapHelper; 23 | import android.support.v7.widget.RecyclerView; 24 | import android.support.v7.widget.Toolbar; 25 | import android.view.View; 26 | import android.widget.FrameLayout; 27 | import android.widget.LinearLayout; 28 | import android.widget.RelativeLayout; 29 | import android.widget.TextView; 30 | import android.widget.Toast; 31 | 32 | import com.winfo.photoselector.adapter.BottomPreviewAdapter; 33 | import com.winfo.photoselector.adapter.PreviewImageAdapter; 34 | import com.winfo.photoselector.entity.Image; 35 | import com.winfo.photoselector.utils.ImageUtil; 36 | import com.winfo.photoselector.utils.StatusBarUtils; 37 | 38 | import java.util.ArrayList; 39 | import java.util.List; 40 | 41 | import static android.animation.ObjectAnimator.ofFloat; 42 | 43 | public class RvPreviewActivity extends AppCompatActivity { 44 | 45 | private RecyclerView recyclerView; 46 | private LinearLayoutManager linearLayoutManager; 47 | // private TextView tvIndicator; 48 | private TextView tvConfirm; 49 | private FrameLayout btnConfirm; 50 | private TextView tvSelect; 51 | private RelativeLayout rlBottomBar; 52 | private AppBarLayout appBarLayout; 53 | private Toolbar toolbar; 54 | 55 | //tempImages和tempSelectImages用于图片列表数据的页面传输。 56 | //之所以不要Intent传输这两个图片列表,因为要保证两位页面操作的是同一个列表数据,同时可以避免数据量大时, 57 | // 用Intent传输发生的错误问题。 58 | private static ArrayList tempImages; 59 | private static ArrayList tempSelectImages; 60 | 61 | private ArrayList mImages; 62 | private ArrayList mSelectImages; 63 | private boolean isShowBar = true; 64 | private boolean isConfirm = false; 65 | private boolean isSingle; 66 | private int mMaxCount; 67 | 68 | private BitmapDrawable mSelectDrawable; 69 | private BitmapDrawable mUnSelectDrawable; 70 | 71 | /*-----------------------------------*/ 72 | private RecyclerView bottomRecycleview; 73 | private BottomPreviewAdapter bottomPreviewAdapter; 74 | private View line; 75 | private boolean isPreview;//是否点击预览按钮进入此页面 76 | 77 | /** 78 | * @param activity activity 79 | * @param images images 80 | * @param selectImages 选中的图片 81 | * @param isSingle 是否单选 82 | * @param maxSelectCount 最大选择数 83 | * @param position posttion 84 | * @param toolBarColor toolBarColor颜色值 85 | * @param bottomBarColor bottomBarColor颜色值 86 | * @param statusBarColor statusBarColor颜色值 87 | */ 88 | public static void openActivity(boolean isPreview, Activity activity, ArrayList images, 89 | ArrayList selectImages, 90 | boolean isSingle, 91 | int maxSelectCount, 92 | int position, 93 | @ColorInt int toolBarColor, 94 | @ColorInt int bottomBarColor, 95 | @ColorInt int statusBarColor) { 96 | tempImages = images; 97 | tempSelectImages = selectImages; 98 | Intent intent = new Intent(activity, RvPreviewActivity.class); 99 | intent.putExtra(PhotoSelector.EXTRA_MAX_SELECTED_COUNT, maxSelectCount); 100 | intent.putExtra(PhotoSelector.EXTRA_SINGLE, isSingle); 101 | intent.putExtra(PhotoSelector.EXTRA_POSITION, position); 102 | intent.putExtra(PhotoSelector.EXTRA_ISPREVIEW, isPreview); 103 | intent.putExtra(PhotoSelector.EXTRA_TOOLBARCOLOR, toolBarColor); 104 | intent.putExtra(PhotoSelector.EXTRA_BOTTOMBARCOLOR, bottomBarColor); 105 | intent.putExtra(PhotoSelector.EXTRA_STATUSBARCOLOR, statusBarColor); 106 | activity.startActivityForResult(intent, PhotoSelector.RESULT_CODE); 107 | // ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, imageView, "aa"); 108 | // //与xml文件对应 109 | // ActivityCompat.startActivityForResult(activity, intent, Constants.RESULT_CODE, options.toBundle()); 110 | } 111 | 112 | 113 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 114 | @SuppressLint("SetTextI18n") 115 | @Override 116 | protected void onCreate(@Nullable Bundle savedInstanceState) { 117 | super.onCreate(savedInstanceState); 118 | setContentView(R.layout.activity_rv_preview); 119 | appBarLayout = findViewById(R.id.appbar); 120 | toolbar = findViewById(R.id.toolbar); 121 | setSupportActionBar(toolbar); 122 | ActionBar actionBar = getSupportActionBar(); 123 | assert actionBar != null; 124 | actionBar.setDisplayHomeAsUpEnabled(true); 125 | toolbar.setNavigationOnClickListener(new View.OnClickListener() { 126 | @Override 127 | public void onClick(View v) { 128 | finish(); 129 | } 130 | }); 131 | 132 | setStatusBarVisible(true); 133 | mImages = tempImages; 134 | tempImages = null; 135 | mSelectImages = tempSelectImages; 136 | tempSelectImages = null; 137 | 138 | Intent intent = getIntent(); 139 | mMaxCount = intent.getIntExtra(PhotoSelector.EXTRA_MAX_SELECTED_COUNT, 0); 140 | isSingle = intent.getBooleanExtra(PhotoSelector.EXTRA_SINGLE, false); 141 | isPreview = intent.getBooleanExtra(PhotoSelector.EXTRA_ISPREVIEW, false); 142 | Resources resources = getResources(); 143 | Bitmap selectBitmap = ImageUtil.getBitmap(this, R.drawable.ic_image_select); 144 | mSelectDrawable = new BitmapDrawable(resources, selectBitmap); 145 | mSelectDrawable.setBounds(0, 0, selectBitmap.getWidth(), selectBitmap.getHeight()); 146 | 147 | Bitmap unSelectBitmap = ImageUtil.getBitmap(this, R.drawable.ic_image_un_select); 148 | mUnSelectDrawable = new BitmapDrawable(resources, unSelectBitmap); 149 | mUnSelectDrawable.setBounds(0, 0, unSelectBitmap.getWidth(), unSelectBitmap.getHeight()); 150 | 151 | int toolBarColor = intent.getIntExtra(PhotoSelector.EXTRA_TOOLBARCOLOR, ContextCompat.getColor(this, R.color.blue)); 152 | int bottomBarColor = intent.getIntExtra(PhotoSelector.EXTRA_BOTTOMBARCOLOR, ContextCompat.getColor(this, R.color.blue)); 153 | int statusBarColor = intent.getIntExtra(PhotoSelector.EXTRA_STATUSBARCOLOR, ContextCompat.getColor(this, R.color.blue)); 154 | 155 | initView(); 156 | 157 | StatusBarUtils.setBarColor(this, statusBarColor); 158 | setToolBarColor(toolBarColor); 159 | setBottomBarColor(bottomBarColor); 160 | initListener(); 161 | initViewPager(); 162 | 163 | 164 | changeSelect(mImages.get(intent.getIntExtra(PhotoSelector.EXTRA_POSITION, 0))); 165 | // vpImage.setCurrentItem(intent.getIntExtra(Constants.POSITION, 0)); 166 | recyclerView.scrollToPosition(intent.getIntExtra(PhotoSelector.EXTRA_POSITION, 0)); 167 | toolbar.setTitle(intent.getIntExtra(PhotoSelector.EXTRA_POSITION, 0) + 1 + "/" + mImages.size()); 168 | if (isPreview) { 169 | bottomRecycleview.smoothScrollToPosition(0); 170 | } 171 | // tvIndicator.setText(); 172 | 173 | } 174 | 175 | private void initView() { 176 | recyclerView = findViewById(R.id.rv_preview); 177 | // tvIndicator = findViewById(R.id.tv_indicator); 178 | tvConfirm = findViewById(R.id.tv_confirm); 179 | btnConfirm = findViewById(R.id.btn_confirm); 180 | tvSelect = findViewById(R.id.tv_select); 181 | rlBottomBar = findViewById(R.id.rl_bottom_bar); 182 | bottomRecycleview = findViewById(R.id.bottom_recycleview); 183 | line = findViewById(R.id.line); 184 | bottomRecycleview.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false)); 185 | if (mSelectImages.size() == 0) { 186 | bottomRecycleview.setVisibility(View.GONE); 187 | line.setVisibility(View.GONE); 188 | } 189 | bottomPreviewAdapter = new BottomPreviewAdapter(this, mSelectImages); 190 | bottomRecycleview.setAdapter(bottomPreviewAdapter); 191 | // LinearSnapHelper snapHelper = new LinearSnapHelper(); 192 | // snapHelper.attachToRecyclerView(bottomRecycleview); 193 | } 194 | 195 | private void initListener() { 196 | btnConfirm.setOnClickListener(new View.OnClickListener() { 197 | @Override 198 | public void onClick(View v) { 199 | isConfirm = true; 200 | finish(); 201 | } 202 | }); 203 | 204 | tvSelect.setOnClickListener(new View.OnClickListener() { 205 | @Override 206 | public void onClick(View v) { 207 | clickSelect(); 208 | } 209 | }); 210 | 211 | bottomPreviewAdapter.setOnItemClcikLitener(new BottomPreviewAdapter.OnItemClcikLitener() { 212 | @Override 213 | public void OnItemClcik(int position, Image image) { 214 | if (isPreview) { 215 | List imageList = previewImageAdapter.getData(); 216 | for (int i = 0; i < imageList.size(); i++) { 217 | if (imageList.get(i).equals(image)) { 218 | recyclerView.smoothScrollToPosition(i); 219 | } 220 | } 221 | } else { 222 | recyclerView.smoothScrollToPosition(mSelectImages.get(position).getPosition()); 223 | } 224 | bottomPreviewAdapter.notifyDataSetChanged(); 225 | } 226 | }); 227 | } 228 | 229 | /** 230 | * 初始化ViewPager 231 | */ 232 | private PreviewImageAdapter previewImageAdapter; 233 | 234 | private void initViewPager() { 235 | recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); 236 | linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); 237 | previewImageAdapter = new PreviewImageAdapter(this, mImages); 238 | recyclerView.setAdapter(previewImageAdapter); 239 | PagerSnapHelper snapHelper = new PagerSnapHelper(); 240 | // LinearSnapHelper snapHelper = new LinearSnapHelper(); 241 | snapHelper.attachToRecyclerView(recyclerView); 242 | 243 | previewImageAdapter.setOnItemClcikLitener(new PreviewImageAdapter.OnItemClcikLitener() { 244 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 245 | @Override 246 | public void OnItemClcik(PreviewImageAdapter previewImageAdapter, View iteView, int position) { 247 | if (isShowBar) { 248 | hideBar(); 249 | } else { 250 | showBar(); 251 | } 252 | } 253 | }); 254 | recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { 255 | @SuppressLint("SetTextI18n") 256 | @Override 257 | public void onScrollStateChanged(RecyclerView recyclerView, int newState) { 258 | super.onScrollStateChanged(recyclerView, newState); 259 | if (newState == RecyclerView.SCROLL_STATE_IDLE) { 260 | int position = linearLayoutManager.findLastVisibleItemPosition(); 261 | mImages.get(position).setPosition(position); 262 | toolbar.setTitle((position + 1) + "/" + mImages.size()); 263 | changeSelect(mImages.get(position)); 264 | } 265 | } 266 | }); 267 | 268 | } 269 | 270 | 271 | /** 272 | * 修改topbar的颜色 273 | * 274 | * @param color 颜色值 275 | */ 276 | private void setToolBarColor(@ColorInt int color) { 277 | toolbar.setBackgroundColor(color); 278 | } 279 | 280 | /** 281 | * 修改bottombar的颜色 282 | * 283 | * @param color 颜色值 284 | */ 285 | private void setBottomBarColor(@ColorInt int color) { 286 | rlBottomBar.setBackgroundColor(color); 287 | } 288 | 289 | 290 | /** 291 | * 显示和隐藏状态栏 292 | * 293 | * @param show 是否显示 294 | */ 295 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 296 | private void setStatusBarVisible(boolean show) { 297 | if (show) { 298 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 299 | } else { 300 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 301 | | View.SYSTEM_UI_FLAG_FULLSCREEN); 302 | } 303 | } 304 | 305 | /** 306 | * 显示头部和尾部栏 307 | */ 308 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 309 | private void showBar() { 310 | isShowBar = true; 311 | setStatusBarVisible(true); 312 | //添加延时,保证StatusBar完全显示后再进行动画。 313 | appBarLayout.postDelayed(new Runnable() { 314 | @Override 315 | public void run() { 316 | if (appBarLayout != null) { 317 | ObjectAnimator animator = ofFloat(appBarLayout, "translationY", 318 | appBarLayout.getTranslationY(), 0).setDuration(300); 319 | animator.addListener(new AnimatorListenerAdapter() { 320 | @Override 321 | public void onAnimationStart(Animator animation) { 322 | super.onAnimationStart(animation); 323 | if (appBarLayout != null) { 324 | appBarLayout.setVisibility(View.VISIBLE); 325 | } 326 | } 327 | }); 328 | animator.start(); 329 | ofFloat(rlBottomBar, "translationY", rlBottomBar.getTranslationY(), 0) 330 | .setDuration(300).start(); 331 | } 332 | } 333 | }, 100); 334 | } 335 | 336 | /** 337 | * 隐藏头部和尾部栏 338 | */ 339 | private void hideBar() { 340 | isShowBar = false; 341 | ObjectAnimator animator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 342 | 0, -appBarLayout.getHeight()).setDuration(300); 343 | animator.addListener(new AnimatorListenerAdapter() { 344 | @Override 345 | public void onAnimationEnd(Animator animation) { 346 | super.onAnimationEnd(animation); 347 | if (appBarLayout != null) { 348 | appBarLayout.setVisibility(View.GONE); 349 | //添加延时,保证rlTopBar完全隐藏后再隐藏StatusBar。 350 | appBarLayout.postDelayed(new Runnable() { 351 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 352 | @Override 353 | public void run() { 354 | setStatusBarVisible(false); 355 | } 356 | }, 5); 357 | } 358 | } 359 | }); 360 | animator.start(); 361 | ofFloat(rlBottomBar, "translationY", 0, rlBottomBar.getHeight()) 362 | .setDuration(300).start(); 363 | } 364 | 365 | private void clickSelect() { 366 | final int position = linearLayoutManager.findFirstVisibleItemPosition(); 367 | if (mImages != null && mImages.size() > position) { 368 | Image image = mImages.get(position); 369 | if (mSelectImages.contains(image)) { 370 | mSelectImages.remove(image); 371 | } else if (isSingle) { 372 | mSelectImages.clear(); 373 | mSelectImages.add(image); 374 | } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) { 375 | // image.setSelectPosition(mSelectImages.size()); 376 | mSelectImages.add(image); 377 | } else { 378 | Toast.makeText(RvPreviewActivity.this, "最多只能选" + mMaxCount + "张", Toast.LENGTH_SHORT).show(); 379 | } 380 | bottomPreviewAdapter.referesh(mSelectImages); 381 | bottomPreviewAdapter.notifyDataSetChanged(); 382 | changeSelect(image); 383 | } 384 | if (mSelectImages.size() > 0) { 385 | bottomRecycleview.setVisibility(View.VISIBLE); 386 | line.setVisibility(View.VISIBLE); 387 | } else { 388 | bottomRecycleview.setVisibility(View.GONE); 389 | line.setVisibility(View.GONE); 390 | } 391 | } 392 | 393 | private void changeSelect(Image image) { 394 | tvSelect.setCompoundDrawables(mSelectImages.contains(image) ? 395 | mSelectDrawable : mUnSelectDrawable, null, null, null); 396 | setSelectImageCount(mSelectImages.size()); 397 | //清空所有选择的照片的边框背景 398 | for (Image image1 : mSelectImages) { 399 | image1.setChecked(false); 400 | } 401 | //设置当前选中打的照片的背景 402 | image.setChecked(true); 403 | bottomPreviewAdapter.referesh(mSelectImages); 404 | bottomPreviewAdapter.notifyDataSetChanged(); 405 | if (mSelectImages.contains(image)) { 406 | bottomRecycleview.smoothScrollToPosition(image.getSelectPosition()); 407 | } 408 | } 409 | 410 | private void setSelectImageCount(int count) { 411 | if (count == 0) { 412 | btnConfirm.setEnabled(false); 413 | tvConfirm.setText(getString(R.string.confirm)); 414 | } else { 415 | btnConfirm.setEnabled(true); 416 | if (isSingle) { 417 | tvConfirm.setText(getString(R.string.confirm)); 418 | } else if (mMaxCount > 0) { 419 | tvConfirm.setText(getString(R.string.confirm_maxcount, count, mMaxCount)); 420 | } else { 421 | tvConfirm.setText(getString(R.string.confirm_count, count)); 422 | } 423 | } 424 | } 425 | 426 | @Override 427 | public void finish() { 428 | //Activity关闭时,通过Intent把用户的操作(确定/返回)传给ImageSelectActivity。 429 | Intent intent = new Intent(); 430 | intent.putExtra(PhotoSelector.IS_CONFIRM, isConfirm); 431 | setResult(PhotoSelector.RESULT_CODE, intent); 432 | super.finish(); 433 | } 434 | } 435 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/adapter/BottomPreviewAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.adapter; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.RequiresApi; 7 | import android.support.v4.content.ContextCompat; 8 | import android.support.v7.widget.RecyclerView; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.widget.ImageView; 13 | import com.bumptech.glide.Glide; 14 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 15 | import com.bumptech.glide.request.RequestOptions; 16 | import com.winfo.photoselector.R; 17 | import com.winfo.photoselector.entity.Image; 18 | 19 | import java.util.List; 20 | 21 | public class BottomPreviewAdapter extends RecyclerView.Adapter { 22 | 23 | private Context context; 24 | private List imagesList; 25 | 26 | public interface OnItemClcikLitener { 27 | void OnItemClcik(int position,Image image); 28 | } 29 | 30 | public OnItemClcikLitener onItemClcikLitener; 31 | 32 | public void setOnItemClcikLitener(OnItemClcikLitener onItemClcikLitener) { 33 | this.onItemClcikLitener = onItemClcikLitener; 34 | } 35 | 36 | public interface OnDataChangeFinishListener { 37 | void changeFinish(); 38 | } 39 | 40 | public OnDataChangeFinishListener onDataChangeFinishListener; 41 | 42 | public void setOnDataChangeFinishListener(OnDataChangeFinishListener onDataChangeFinishListener) { 43 | this.onDataChangeFinishListener = onDataChangeFinishListener; 44 | } 45 | 46 | public BottomPreviewAdapter(Context context, List imagesList) { 47 | this.context = context; 48 | this.imagesList = imagesList; 49 | } 50 | 51 | 52 | @NonNull 53 | @Override 54 | public CustomeHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 55 | return new CustomeHolder(LayoutInflater.from(context).inflate(R.layout.bootm_preview_item, parent, false)); 56 | } 57 | 58 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 59 | @Override 60 | public void onBindViewHolder(@NonNull final CustomeHolder holder, int position) { 61 | imagesList.get(position).setSelectPosition(position); 62 | Glide.with(context).load(imagesList.get(holder.getAdapterPosition()).getPath()) 63 | // .transition(new GenericTransitionOptions<>().transition(R.anim.glide_anim)) 64 | // .transition(new GenericTransitionOptions<>().transition(android.R.anim.slide_in_left)) 65 | // .transition(new DrawableTransitionOptions().crossFade(300)) 66 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE) 67 | .centerCrop() 68 | .override(800, 800)) 69 | .thumbnail(0.5f) 70 | .into(holder.imageView); 71 | holder.imageView.setOnClickListener(new View.OnClickListener() { 72 | @Override 73 | public void onClick(View v) { 74 | for (Image image : imagesList) { 75 | image.setChecked(false); 76 | } 77 | imagesList.get(holder.getAdapterPosition()).setChecked(true); 78 | if (onItemClcikLitener != null) { 79 | int a = holder.getAdapterPosition(); 80 | onItemClcikLitener.OnItemClcik(holder.getAdapterPosition(),imagesList.get(holder.getAdapterPosition())); 81 | } 82 | } 83 | }); 84 | if (imagesList.get(position).isChecked()) { 85 | holder.imageView.setBackground(ContextCompat.getDrawable(context, R.drawable.border)); 86 | } else { 87 | holder.imageView.setBackground(null); 88 | } 89 | } 90 | 91 | @Override 92 | public int getItemCount() { 93 | return imagesList.size(); 94 | } 95 | 96 | class CustomeHolder extends RecyclerView.ViewHolder { 97 | 98 | private ImageView imageView; 99 | 100 | public CustomeHolder(View itemView) { 101 | super(itemView); 102 | imageView = itemView.findViewById(R.id.bottom_imageview_item); 103 | } 104 | } 105 | 106 | public void referesh(List newData) { 107 | this.imagesList = newData; 108 | notifyDataSetChanged(); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/adapter/FolderAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.adapter; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.support.annotation.NonNull; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.ImageView; 11 | import android.widget.TextView; 12 | import com.bumptech.glide.Glide; 13 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 14 | import com.bumptech.glide.request.RequestOptions; 15 | import com.winfo.photoselector.R; 16 | import com.winfo.photoselector.entity.Folder; 17 | import com.winfo.photoselector.entity.Image; 18 | import java.io.File; 19 | import java.util.ArrayList; 20 | 21 | public class FolderAdapter extends RecyclerView.Adapter { 22 | 23 | private Context mContext; 24 | private ArrayList mFolders; 25 | private LayoutInflater mInflater; 26 | private int mSelectItem; 27 | private OnFolderSelectListener mListener; 28 | 29 | public FolderAdapter(Context context, ArrayList folders) { 30 | mContext = context; 31 | mFolders = folders; 32 | this.mInflater = LayoutInflater.from(context); 33 | } 34 | 35 | @NonNull 36 | @Override 37 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 38 | View view = mInflater.inflate(R.layout.adapter_folder, parent, false); 39 | return new ViewHolder(view); 40 | } 41 | 42 | @SuppressLint("SetTextI18n") 43 | @Override 44 | public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { 45 | final Folder folder = mFolders.get(position); 46 | ArrayList images = folder.getImages(); 47 | holder.tvFolderName.setText(folder.getName()); 48 | holder.ivSelect.setVisibility(mSelectItem == position ? View.VISIBLE : View.GONE); 49 | if (images != null && !images.isEmpty()) { 50 | holder.tvFolderSize.setText(images.size() + "张"); 51 | Glide.with(mContext).load(new File(images.get(0).getPath())) 52 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)) 53 | .into(holder.ivImage); 54 | } else { 55 | holder.tvFolderSize.setText("0张"); 56 | holder.ivImage.setImageBitmap(null); 57 | } 58 | 59 | holder.itemView.setOnClickListener(new View.OnClickListener() { 60 | @Override 61 | public void onClick(View v) { 62 | mSelectItem = holder.getAdapterPosition(); 63 | notifyDataSetChanged(); 64 | if (mListener != null) { 65 | mListener.OnFolderSelect(folder); 66 | } 67 | } 68 | }); 69 | } 70 | 71 | @Override 72 | public int getItemCount() { 73 | return mFolders == null ? 0 : mFolders.size(); 74 | } 75 | 76 | public void setOnFolderSelectListener(OnFolderSelectListener listener) { 77 | this.mListener = listener; 78 | } 79 | 80 | static class ViewHolder extends RecyclerView.ViewHolder { 81 | 82 | ImageView ivImage; 83 | ImageView ivSelect; 84 | TextView tvFolderName; 85 | TextView tvFolderSize; 86 | 87 | ViewHolder(View itemView) { 88 | super(itemView); 89 | ivImage = itemView.findViewById(R.id.iv_image); 90 | ivSelect = itemView.findViewById(R.id.iv_select); 91 | tvFolderName = itemView.findViewById(R.id.tv_folder_name); 92 | tvFolderSize = itemView.findViewById(R.id.tv_folder_size); 93 | } 94 | } 95 | 96 | public interface OnFolderSelectListener { 97 | void OnFolderSelect(Folder folder); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/adapter/ImageAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.adapter; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.RequiresApi; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.ImageView; 12 | import android.widget.Toast; 13 | import com.bumptech.glide.GenericTransitionOptions; 14 | import com.bumptech.glide.Glide; 15 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 16 | import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; 17 | import com.bumptech.glide.request.RequestOptions; 18 | import com.winfo.photoselector.R; 19 | import com.winfo.photoselector.entity.Image; 20 | 21 | import java.util.ArrayList; 22 | 23 | public class ImageAdapter extends RecyclerView.Adapter { 24 | 25 | private Context mContext; 26 | private ArrayList mImages; 27 | private LayoutInflater mInflater; 28 | private View.OnClickListener onCameraClickListener = null; 29 | private final static int ITEM_TYPE_CAMERA = 100; 30 | private final static int ITEM_TYPE_PHOTO = 101; 31 | //是否是显示全部图片 只有显示全部图片的时候 才会去显示牌照,否则不显示牌拍照 32 | private boolean showCamera; 33 | 34 | //保存选中的图片 35 | private ArrayList mSelectImages = new ArrayList<>(); 36 | private OnImageSelectListener mSelectListener; 37 | private OnItemClickListener mItemClickListener; 38 | private int mMaxCount; 39 | private boolean isSingle; 40 | 41 | @Override 42 | public int getItemViewType(int position) { 43 | if (showCamera && position == 0) { 44 | return ITEM_TYPE_CAMERA; 45 | } else { 46 | return ITEM_TYPE_PHOTO; 47 | } 48 | } 49 | 50 | /** 51 | * @param maxCount 图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。 52 | * @param isSingle 是否单选 53 | */ 54 | public ImageAdapter(Context context, int maxCount, boolean isSingle) { 55 | mContext = context; 56 | this.mInflater = LayoutInflater.from(mContext); 57 | mMaxCount = maxCount; 58 | this.isSingle = isSingle; 59 | } 60 | 61 | @NonNull 62 | @Override 63 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 64 | if (viewType == ITEM_TYPE_CAMERA) { 65 | CameraHolder cameraHolder = new CameraHolder(mInflater.inflate(R.layout.adapter_camera_item, parent, false)); 66 | cameraHolder.itemView.setOnClickListener(new View.OnClickListener() { 67 | @Override 68 | public void onClick(View v) { 69 | if (onCameraClickListener != null) { 70 | onCameraClickListener.onClick(v); 71 | } 72 | } 73 | }); 74 | return cameraHolder; 75 | } else { 76 | return new ImageHolder(mInflater.inflate(R.layout.adapter_images_item, parent, false)); 77 | } 78 | } 79 | 80 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 81 | @Override 82 | public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { 83 | //如果是照片则加载照片显示 否则的话就是拍照就不用处理,默认用布局显示样式 84 | if (getItemViewType(position) == ITEM_TYPE_PHOTO) { 85 | final ImageHolder imageHolder = (ImageHolder) holder; 86 | final Image image; 87 | //如果是显示拍照 88 | if (showCamera) { 89 | image = mImages.get(position - 1); 90 | image.setPosition(position - 1); 91 | } else { 92 | image = mImages.get(position); 93 | image.setPosition(position); 94 | } 95 | Glide.with(mContext).load(image.getPath()) 96 | // .transition(new GenericTransitionOptions<>().transition(R.anim.glide_anim)) 97 | .transition(new GenericTransitionOptions<>().transition(android.R.anim.slide_in_left)) 98 | .transition(new DrawableTransitionOptions().crossFade(150)) 99 | .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE) 100 | .centerCrop() 101 | .placeholder(R.drawable.ic_image).error(R.drawable.ic_img_load_fail)) 102 | .thumbnail(0.5f) 103 | .into(imageHolder.ivImage); 104 | 105 | setItemSelect(imageHolder, mSelectImages.contains(image)); 106 | //点击选中/取消选中图片 107 | imageHolder.ivSelectIcon.setOnClickListener(new View.OnClickListener() { 108 | @Override 109 | public void onClick(View v) { 110 | // Toast.makeText(mContext , image.getPosition()+"" ,Toast.LENGTH_SHORT).show(); 111 | if (mSelectImages.contains(image)) { 112 | //如果图片已经选中,就取消选中 113 | unSelectImage(image); 114 | setItemSelect(imageHolder, false); 115 | } else if (isSingle) { 116 | //如果是单选,就先清空已经选中的图片,再选中当前图片 117 | clearImageSelect(); 118 | selectImage(image); 119 | setItemSelect(imageHolder, true); 120 | } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) { 121 | //如果不限制图片的选中数量,或者图片的选中数量 122 | // 还没有达到最大限制,就直接选中当前图片。 123 | selectImage(image); 124 | setItemSelect(imageHolder, true); 125 | } else if (mSelectImages.size() == mMaxCount) { 126 | Toast.makeText(mContext, "最多只能选" + mMaxCount + "张", Toast.LENGTH_SHORT).show(); 127 | } 128 | } 129 | }); 130 | 131 | holder.itemView.setOnClickListener(new View.OnClickListener() { 132 | @Override 133 | public void onClick(View v) { 134 | if (mItemClickListener != null) { 135 | //如果是显示拍照 136 | if (showCamera) { 137 | mItemClickListener.OnItemClick(image, imageHolder.itemView, imageHolder.getAdapterPosition() - 1); 138 | } else { 139 | mItemClickListener.OnItemClick(image, imageHolder.itemView, imageHolder.getAdapterPosition()); 140 | } 141 | } 142 | } 143 | }); 144 | } 145 | } 146 | 147 | public void setOnCameraClickListener(View.OnClickListener onCameraClickListener) { 148 | this.onCameraClickListener = onCameraClickListener; 149 | } 150 | 151 | /** 152 | * 选中图片 153 | * 154 | * @param image image 155 | */ 156 | private void selectImage(Image image) { 157 | // image.setSelectPosition(mSelectImages.size()); 158 | mSelectImages.add(image); 159 | if (mSelectListener != null) { 160 | mSelectListener.OnImageSelect(image, true, mSelectImages.size()); 161 | } 162 | } 163 | 164 | /** 165 | * 取消选中图片 166 | * 167 | * @param image image 168 | */ 169 | private void unSelectImage(Image image) { 170 | mSelectImages.remove(image); 171 | if (mSelectListener != null) { 172 | mSelectListener.OnImageSelect(image, false, mSelectImages.size()); 173 | } 174 | } 175 | 176 | @Override 177 | public int getItemCount() { 178 | if (showCamera) { 179 | return mImages == null ? 0 : mImages.size() + 1; 180 | } else { 181 | return mImages == null ? 0 : mImages.size(); 182 | } 183 | } 184 | 185 | public ArrayList getData() { 186 | return mImages; 187 | } 188 | 189 | /** 190 | * 刷新数据 191 | * 192 | * @param data data 193 | * @param showCamera 是否显示拍照功能 194 | */ 195 | public void refresh(ArrayList data, boolean showCamera) { 196 | this.showCamera = showCamera; 197 | mImages = data; 198 | notifyDataSetChanged(); 199 | } 200 | 201 | 202 | /** 203 | * 设置图片选中和未选中的效果 204 | */ 205 | private void setItemSelect(ImageHolder holder, boolean isSelect) { 206 | if (isSelect) { 207 | holder.ivSelectIcon.setImageResource(R.drawable.ic_image_select); 208 | holder.ivMasking.setAlpha(0.5f); 209 | } else { 210 | holder.ivSelectIcon.setImageResource(R.drawable.ic_image_un_select); 211 | holder.ivMasking.setAlpha(0.2f); 212 | } 213 | } 214 | 215 | private void clearImageSelect() { 216 | mSelectImages.clear(); 217 | notifyDataSetChanged(); 218 | // if (mImages != null && mSelectImages.size() == 1) { 219 | // int index = mImages.indexOf(mSelectImages.get(0)); 220 | // if (index != -1) { 221 | // mSelectImages.clear(); 222 | // notifyItemChanged(index); 223 | // notifyDataSetChanged(); 224 | // } 225 | // } 226 | } 227 | 228 | public void setSelectedImages(ArrayList selected) { 229 | mSelectImages.clear(); 230 | if (mImages != null && selected != null) { 231 | for (String path : selected) { 232 | if (isFull()) { 233 | return; 234 | } 235 | for (Image image : mImages) { 236 | if (path.equals(image.getPath())) { 237 | if (!mSelectImages.contains(image)) { 238 | mSelectImages.add(image); 239 | } 240 | break; 241 | } 242 | } 243 | } 244 | notifyDataSetChanged(); 245 | } 246 | } 247 | 248 | 249 | private boolean isFull() { 250 | return isSingle && mSelectImages.size() == 1 || mMaxCount > 0 && mSelectImages.size() == mMaxCount; 251 | } 252 | 253 | public ArrayList getSelectImages() { 254 | return mSelectImages; 255 | } 256 | 257 | public void setOnImageSelectListener(OnImageSelectListener listener) { 258 | this.mSelectListener = listener; 259 | } 260 | 261 | public void setOnItemClickListener(OnItemClickListener listener) { 262 | this.mItemClickListener = listener; 263 | } 264 | 265 | class ImageHolder extends RecyclerView.ViewHolder { 266 | 267 | ImageView ivImage; 268 | ImageView ivSelectIcon; 269 | ImageView ivMasking; 270 | 271 | ImageHolder(View itemView) { 272 | super(itemView); 273 | ivImage = itemView.findViewById(R.id.iv_image); 274 | ivSelectIcon = itemView.findViewById(R.id.iv_select); 275 | ivMasking = itemView.findViewById(R.id.iv_masking); 276 | } 277 | } 278 | 279 | class CameraHolder extends RecyclerView.ViewHolder { 280 | 281 | ImageView ivCamera; 282 | 283 | CameraHolder(View itemView) { 284 | super(itemView); 285 | ivCamera = itemView.findViewById(R.id.iv_camera); 286 | } 287 | } 288 | 289 | public interface OnImageSelectListener { 290 | void OnImageSelect(Image image, boolean isSelect, int selectCount); 291 | } 292 | 293 | public interface OnItemClickListener { 294 | void OnItemClick(Image image, View iteView, int position); 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/adapter/ImagePagerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.adapter; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import android.support.annotation.NonNull; 6 | import android.support.v4.view.PagerAdapter; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.ImageView; 11 | import com.bumptech.glide.Glide; 12 | import com.bumptech.glide.request.RequestOptions; 13 | import com.winfo.photoselector.R; 14 | import com.winfo.photoselector.entity.Image; 15 | 16 | import java.io.File; 17 | import java.util.List; 18 | 19 | public class ImagePagerAdapter extends PagerAdapter { 20 | 21 | private Context mContext; 22 | // private List viewList = new ArrayList<>(4); 23 | private List mImgList; 24 | private OnItemClickListener mListener; 25 | 26 | public ImagePagerAdapter(Context context, List imgList) { 27 | this.mContext = context; 28 | // createImageViews(); 29 | mImgList = imgList; 30 | } 31 | 32 | // private void createImageViews() { 33 | // for (int i = 0; i < 4; i++) { 34 | // PhotoView imageView = new PhotoView(mContext); 35 | // imageView.setAdjustViewBounds(true); 36 | // viewList.add(imageView); 37 | // } 38 | // } 39 | 40 | @Override 41 | public int getCount() { 42 | return mImgList == null ? 0 : mImgList.size(); 43 | } 44 | 45 | @Override 46 | public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { 47 | return view == object; 48 | } 49 | 50 | @Override 51 | public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { 52 | // if (object instanceof PhotoView) { 53 | // PhotoView view = (PhotoView) object; 54 | // view.setImageDrawable(null); 55 | // viewList.add(view); 56 | // container.removeView(view); 57 | // } 58 | container.removeView((View) object); 59 | } 60 | 61 | @Override 62 | public int getItemPosition(@NonNull Object object) { 63 | return POSITION_NONE; 64 | } 65 | 66 | @NonNull 67 | @Override 68 | public Object instantiateItem(@NonNull ViewGroup container, final int position) { 69 | View itemView = LayoutInflater.from(mContext) 70 | .inflate(R.layout.item_view_pager, container, false); 71 | final ImageView imageView = itemView.findViewById(R.id.iv_pager); 72 | 73 | final String path = mImgList.get(position).getPath(); 74 | 75 | final Uri uri; 76 | if (path.startsWith("http")) { 77 | uri = Uri.parse(path); 78 | } else { 79 | uri = Uri.fromFile(new File(path)); 80 | } 81 | final Image image = mImgList.get(position); 82 | Glide.with(mContext).setDefaultRequestOptions(new RequestOptions() 83 | .dontTransform() 84 | .placeholder(R.drawable.ic_image) 85 | .error(R.drawable.ic_img_load_fail) 86 | .override(800, 1200)) 87 | .load(uri) 88 | .into(imageView); 89 | 90 | imageView.setOnClickListener(new View.OnClickListener() { 91 | @Override 92 | public void onClick(View v) { 93 | if (mListener != null) { 94 | mListener.onItemClick(position, image); 95 | } 96 | } 97 | }); 98 | container.addView(itemView); 99 | 100 | // final PhotoView currentView = viewList.remove(0); 101 | // final Image image = mImgList.get(position); 102 | // container.addView(currentView); 103 | // Glide.with(mContext).asBitmap() 104 | // .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)) 105 | // .load(new File(image.getPath())).into(new SimpleTarget() { 106 | // @Override 107 | // public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) { 108 | // currentView.setImageBitmap(resource); 109 | //// int bw = resource.getWidth(); 110 | //// int bh = resource.getHeight(); 111 | //// if (bw > 8192 || bh > 8192) { 112 | //// Bitmap bitmap = ImageUtil.zoomBitmap(resource, 8192, 8192); 113 | //// setBitmap(currentView, bitmap); 114 | //// } else { 115 | //// setBitmap(currentView, resource); 116 | //// } 117 | // } 118 | // }); 119 | // currentView.setOnClickListener(new View.OnClickListener() { 120 | // @Override 121 | // public void onClick(View v) { 122 | // if (mListener != null) { 123 | // mListener.onItemClick(position, image); 124 | // } 125 | // } 126 | // }); 127 | return itemView; 128 | } 129 | 130 | // private void setBitmap(PhotoView imageView, Bitmap bitmap) { 131 | // imageView.setImageBitmap(bitmap); 132 | // if (bitmap != null) { 133 | // int bw = bitmap.getWidth(); 134 | // int bh = bitmap.getHeight(); 135 | // int vw = imageView.getWidth(); 136 | // int vh = imageView.getHeight(); 137 | // if (bw != 0 && bh != 0 && vw != 0 && vh != 0) { 138 | // if (1.0f * bh / bw > 1.0f * vh / vw) { 139 | // imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 140 | // float offset = (1.0f * bh * vw / bw - vh) / 2; 141 | // adjustOffset(imageView, offset); 142 | // } else { 143 | // imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); 144 | // } 145 | // } 146 | // } 147 | // } 148 | 149 | public void setOnItemClickListener(OnItemClickListener l) { 150 | mListener = l; 151 | } 152 | 153 | public interface OnItemClickListener { 154 | void onItemClick(int position, Image image); 155 | } 156 | 157 | // private void adjustOffset(PhotoView view, float offset) { 158 | // PhotoViewAttacher attacher = view.getAttacher(); 159 | // try { 160 | // Field field = PhotoViewAttacher.class.getDeclaredField("mBaseMatrix"); 161 | // field.setAccessible(true); 162 | // Matrix matrix = (Matrix) field.get(attacher); 163 | // matrix.postTranslate(0, offset); 164 | // Method method = PhotoViewAttacher.class.getDeclaredMethod("resetMatrix"); 165 | // method.setAccessible(true); 166 | // method.invoke(attacher); 167 | // } catch (Exception e) { 168 | // e.printStackTrace(); 169 | // } 170 | // } 171 | } 172 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/adapter/PreviewImageAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.adapter; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import android.support.annotation.NonNull; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.ImageView; 11 | import com.bumptech.glide.Glide; 12 | import com.bumptech.glide.request.RequestOptions; 13 | import com.winfo.photoselector.R; 14 | import com.winfo.photoselector.entity.Image; 15 | import java.io.File; 16 | import java.util.List; 17 | 18 | /** 19 | * ProjectName:ImageSelector-master 20 | * PackageName:com.donkingliang.imageselector.adapter 21 | * Author:wenjie 22 | * Date:2018-06-14 18:31 23 | * Description: 24 | */ 25 | public class PreviewImageAdapter extends RecyclerView.Adapter { 26 | 27 | private Context mContext; 28 | private List mImgList; 29 | 30 | public interface OnItemClcikLitener { 31 | void OnItemClcik(PreviewImageAdapter previewImageAdapter, View iteView, int position); 32 | } 33 | 34 | public OnItemClcikLitener onItemClcikLitener; 35 | 36 | public void setOnItemClcikLitener(OnItemClcikLitener onItemClcikLitener) { 37 | this.onItemClcikLitener = onItemClcikLitener; 38 | } 39 | 40 | public PreviewImageAdapter(Context mContext, List mImgList) { 41 | this.mContext = mContext; 42 | this.mImgList = mImgList; 43 | } 44 | 45 | public List getData() { 46 | return mImgList; 47 | } 48 | 49 | @NonNull 50 | @Override 51 | public ImageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 52 | final ImageHolder imageHolder = new ImageHolder(LayoutInflater.from(mContext).inflate(R.layout.preview_item, parent, false)); 53 | imageHolder.itemView.setOnClickListener(new View.OnClickListener() { 54 | @Override 55 | public void onClick(View v) { 56 | if (onItemClcikLitener != null){ 57 | onItemClcikLitener.OnItemClcik(PreviewImageAdapter.this , imageHolder.itemView , imageHolder.getLayoutPosition()); 58 | } 59 | } 60 | }); 61 | return imageHolder; 62 | } 63 | 64 | @Override 65 | public void onBindViewHolder(@NonNull ImageHolder holder, int position) { 66 | String path = mImgList.get(position).getPath(); 67 | Uri uri; 68 | if (path.startsWith("http")) { 69 | uri = Uri.parse(path); 70 | } else { 71 | uri = Uri.fromFile(new File(path)); 72 | } 73 | Glide.with(mContext).setDefaultRequestOptions(new RequestOptions() 74 | .dontTransform() 75 | .placeholder(R.drawable.ic_image) 76 | .error(R.drawable.ic_img_load_fail) 77 | .override(800, 1200)) 78 | .load(uri) 79 | .into(holder.imageView); 80 | } 81 | 82 | @Override 83 | public int getItemCount() { 84 | return mImgList.size(); 85 | } 86 | 87 | class ImageHolder extends RecyclerView.ViewHolder { 88 | 89 | private ImageView imageView; 90 | 91 | ImageHolder(View itemView) { 92 | super(itemView); 93 | imageView = itemView.findViewById(R.id.iv_itemimg); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/entity/Folder.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.entity; 2 | 3 | import com.winfo.photoselector.utils.StringUtils; 4 | 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * 图片文件夹实体类 9 | */ 10 | public class Folder { 11 | 12 | private boolean useCamera; // 是否可以调用相机拍照。只有“全部”文件夹才可以拍照 13 | private String name; 14 | private ArrayList images; 15 | 16 | 17 | public Folder(String name) { 18 | this.name = name; 19 | } 20 | 21 | public Folder(String name, ArrayList images) { 22 | this.name = name; 23 | this.images = images; 24 | } 25 | 26 | public boolean isUseCamera() { 27 | return useCamera; 28 | } 29 | 30 | public void setUseCamera(boolean useCamera) { 31 | this.useCamera = useCamera; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | public ArrayList getImages() { 43 | return images; 44 | } 45 | 46 | public void setImages(ArrayList images) { 47 | this.images = images; 48 | } 49 | 50 | public void addImage(Image image) { 51 | if (image != null && StringUtils.isNotEmptyString(image.getPath())) { 52 | if (images == null) { 53 | images = new ArrayList<>(); 54 | } 55 | images.add(image); 56 | } 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "Folder{" + 62 | "name='" + name + '\'' + 63 | ", images=" + images + 64 | '}'; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/entity/Image.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.entity; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | /** 7 | * 图片实体类 8 | */ 9 | public class Image implements Parcelable { 10 | 11 | private String path; 12 | private long time; 13 | private String name; 14 | private int position; 15 | private boolean isChecked; 16 | private int selectPosition; 17 | 18 | public int getSelectPosition() { 19 | return selectPosition; 20 | } 21 | 22 | public void setSelectPosition(int selectPosition) { 23 | this.selectPosition = selectPosition; 24 | } 25 | 26 | public boolean isChecked() { 27 | return isChecked; 28 | } 29 | 30 | public void setChecked(boolean checked) { 31 | isChecked = checked; 32 | } 33 | 34 | public int getPosition() { 35 | return position; 36 | } 37 | 38 | public void setPosition(int position) { 39 | this.position = position; 40 | } 41 | 42 | public Image(String path, long time, String name) { 43 | this.path = path; 44 | this.time = time; 45 | this.name = name; 46 | } 47 | 48 | public String getPath() { 49 | return path; 50 | } 51 | 52 | public void setPath(String path) { 53 | this.path = path; 54 | } 55 | 56 | public long getTime() { 57 | return time; 58 | } 59 | 60 | public void setTime(long time) { 61 | this.time = time; 62 | } 63 | 64 | public String getName() { 65 | return name; 66 | } 67 | 68 | public void setName(String name) { 69 | this.name = name; 70 | } 71 | 72 | @Override 73 | public int describeContents() { 74 | return 0; 75 | } 76 | 77 | @Override 78 | public void writeToParcel(Parcel dest, int flags) { 79 | dest.writeString(this.path); 80 | dest.writeLong(this.time); 81 | dest.writeString(this.name); 82 | } 83 | 84 | protected Image(Parcel in) { 85 | this.path = in.readString(); 86 | this.time = in.readLong(); 87 | this.name = in.readString(); 88 | } 89 | 90 | public static final Creator CREATOR = new Creator() { 91 | @Override 92 | public Image createFromParcel(Parcel source) { 93 | return new Image(source); 94 | } 95 | 96 | @Override 97 | public Image[] newArray(int size) { 98 | return new Image[size]; 99 | } 100 | }; 101 | } 102 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/model/ImageModel.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.model; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.Context; 5 | import android.database.Cursor; 6 | import android.net.Uri; 7 | import android.provider.MediaStore; 8 | import com.winfo.photoselector.entity.Folder; 9 | import com.winfo.photoselector.entity.Image; 10 | import com.winfo.photoselector.utils.StringUtils; 11 | import java.io.File; 12 | import java.util.ArrayList; 13 | import java.util.Collections; 14 | import java.util.List; 15 | 16 | public class ImageModel { 17 | 18 | /** 19 | * 从SDCard加载图片 20 | * 21 | * @param context context 22 | * @param callback 回调 23 | */ 24 | public static void loadImageForSDCard(final Context context, final DataCallback callback) { 25 | //由于扫描图片是耗时的操作,所以要在子线程处理。 26 | new Thread(new Runnable() { 27 | @Override 28 | public void run() { 29 | //扫描图片 30 | Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 31 | ContentResolver mContentResolver = context.getContentResolver(); 32 | 33 | Cursor mCursor = mContentResolver.query(mImageUri, new String[]{ 34 | MediaStore.Images.Media.DATA, 35 | MediaStore.Images.Media.DISPLAY_NAME, 36 | MediaStore.Images.Media.DATE_ADDED, 37 | MediaStore.Images.Media._ID}, 38 | null, 39 | null, 40 | MediaStore.Images.Media.DATE_ADDED); 41 | 42 | ArrayList images = new ArrayList<>(); 43 | 44 | //读取扫描到的图片 45 | if (mCursor != null) { 46 | while (mCursor.moveToNext()) { 47 | // 获取图片的路径 48 | String path = mCursor.getString( 49 | mCursor.getColumnIndex(MediaStore.Images.Media.DATA)); 50 | //获取图片名称 51 | String name = mCursor.getString( 52 | mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)); 53 | //获取图片时间 54 | long time = mCursor.getLong( 55 | mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED)); 56 | if (!".downloading".equals(getExtensionName(path))) { //过滤未下载完成的文件 57 | images.add(new Image(path, time, name)); 58 | } 59 | } 60 | mCursor.close(); 61 | } 62 | Collections.reverse(images); 63 | callback.onSuccess(splitFolder(images)); 64 | } 65 | }).start(); 66 | } 67 | 68 | /** 69 | * 把图片按文件夹拆分,第一个文件夹保存所有的图片 70 | * 71 | * @param images 集合 72 | * @return 图片集合 73 | */ 74 | private static ArrayList splitFolder(ArrayList images) { 75 | ArrayList folders = new ArrayList<>(); 76 | folders.add(new Folder("全部图片", images)); 77 | 78 | if (images != null && !images.isEmpty()) { 79 | int size = images.size(); 80 | for (int i = 0; i < size; i++) { 81 | String path = images.get(i).getPath(); 82 | String name = getFolderName(path); 83 | if (StringUtils.isNotEmptyString(name)) { 84 | Folder folder = getFolder(name, folders); 85 | folder.addImage(images.get(i)); 86 | } 87 | } 88 | } 89 | return folders; 90 | } 91 | 92 | /** 93 | * Java文件操作 获取文件扩展名 94 | */ 95 | private static String getExtensionName(String filename) { 96 | if (filename != null && filename.length() > 0) { 97 | int dot = filename.lastIndexOf('.'); 98 | if (dot > -1 && dot < filename.length() - 1) { 99 | return filename.substring(dot + 1); 100 | } 101 | } 102 | return ""; 103 | } 104 | 105 | /** 106 | * 根据图片路径,获取图片文件夹名称 107 | * 108 | * @param path 文件路径 109 | * @return 文件夹名称 110 | */ 111 | private static String getFolderName(String path) { 112 | if (StringUtils.isNotEmptyString(path)) { 113 | String[] strings = path.split(File.separator); 114 | if (strings.length >= 2) { 115 | return strings[strings.length - 2]; 116 | } 117 | } 118 | return ""; 119 | } 120 | 121 | private static Folder getFolder(String name, List folders) { 122 | if (!folders.isEmpty()) { 123 | int size = folders.size(); 124 | for (int i = 0; i < size; i++) { 125 | Folder folder = folders.get(i); 126 | if (name.equals(folder.getName())) { 127 | return folder; 128 | } 129 | } 130 | } 131 | Folder newFolder = new Folder(name); 132 | folders.add(newFolder); 133 | return newFolder; 134 | } 135 | 136 | public interface DataCallback { 137 | void onSuccess(ArrayList folders); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | import java.util.Locale; 7 | 8 | public class DateUtils { 9 | 10 | public static String getImageTime(long time) { 11 | Calendar calendar = Calendar.getInstance(); 12 | calendar.setTime(new Date()); 13 | Calendar imageTime = Calendar.getInstance(); 14 | imageTime.setTimeInMillis(time); 15 | if (sameDay(calendar, imageTime)) { 16 | return "今天"; 17 | } else if (sameWeek(calendar, imageTime)) { 18 | return "本周"; 19 | } else if (sameMonth(calendar, imageTime)) { 20 | return "本月"; 21 | } else { 22 | Date date = new Date(time); 23 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM", Locale.CANADA); 24 | return sdf.format(date); 25 | } 26 | } 27 | 28 | public static boolean sameDay(Calendar calendar1, Calendar calendar2) { 29 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) 30 | && calendar1.get(Calendar.DAY_OF_YEAR) == calendar2.get(Calendar.DAY_OF_YEAR); 31 | } 32 | 33 | public static boolean sameWeek(Calendar calendar1, Calendar calendar2) { 34 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) 35 | && calendar1.get(Calendar.WEEK_OF_YEAR) == calendar2.get(Calendar.WEEK_OF_YEAR); 36 | } 37 | 38 | public static boolean sameMonth(Calendar calendar1, Calendar calendar2) { 39 | return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) 40 | && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/ImageCaptureManager.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import android.content.ContentValues; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.os.Environment; 10 | import android.provider.MediaStore; 11 | import android.text.TextUtils; 12 | import android.util.Log; 13 | 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.text.SimpleDateFormat; 17 | import java.util.Date; 18 | import java.util.Locale; 19 | 20 | public class ImageCaptureManager { 21 | 22 | private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath"; 23 | public static final String PHOTO_PATH = "photo_path"; 24 | 25 | private String mCurrentPhotoPath; 26 | private Context mContext; 27 | 28 | public ImageCaptureManager(Context mContext) { 29 | this.mContext = mContext; 30 | } 31 | 32 | private File createImageFile() throws IOException { 33 | // Create an image file name 34 | String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date()); 35 | String imageFileName = "JPEG_" + timeStamp + ".jpg"; 36 | File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 37 | 38 | if (!storageDir.exists()) { 39 | if (!storageDir.mkdir()) { 40 | Log.e("TAG", "Throwing Errors...."); 41 | throw new IOException(); 42 | } 43 | } 44 | 45 | File image = new File(storageDir, imageFileName); 46 | 47 | // Save glide_anim file: path for use with ACTION_VIEW intents 48 | mCurrentPhotoPath = image.getAbsolutePath(); 49 | return image; 50 | } 51 | 52 | 53 | public Intent dispatchTakePictureIntent() throws IOException { 54 | Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 55 | // Ensure that there's glide_anim camera activity to handle the intent 56 | if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) { 57 | // Create the File where the photo should go 58 | File file = createImageFile(); 59 | Uri photoFile = null; 60 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 61 | // String authority = mContext.getApplicationInfo().packageName + ".provider"; 62 | // photoFile = FileProvider.getUriForFile(this.mContext.getApplicationContext(), authority, file); 63 | //兼容android7.0 使用共享文件的形式 64 | ContentValues contentValues = new ContentValues(1); 65 | contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); 66 | Uri uri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); 67 | takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); 68 | } else { 69 | photoFile = Uri.fromFile(file); 70 | } 71 | // Continue only if the File was successfully created 72 | if (photoFile != null) { 73 | takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile); 74 | } 75 | takePictureIntent.putExtra(PHOTO_PATH, file.getAbsolutePath()); 76 | } 77 | 78 | return takePictureIntent; 79 | } 80 | 81 | 82 | public void galleryAddPic() { 83 | Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 84 | 85 | if (TextUtils.isEmpty(mCurrentPhotoPath)) { 86 | return; 87 | } 88 | 89 | File f = new File(mCurrentPhotoPath); 90 | Uri contentUri = Uri.fromFile(f); 91 | mediaScanIntent.setData(contentUri); 92 | mContext.sendBroadcast(mediaScanIntent); 93 | } 94 | 95 | 96 | public String getCurrentPhotoPath() { 97 | return mCurrentPhotoPath; 98 | } 99 | 100 | 101 | public void onSaveInstanceState(Bundle savedInstanceState) { 102 | if (savedInstanceState != null && mCurrentPhotoPath != null) { 103 | savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath); 104 | } 105 | } 106 | 107 | public void onRestoreInstanceState(Bundle savedInstanceState) { 108 | if (savedInstanceState != null && savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) { 109 | mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY); 110 | } 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/ImageUtil.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.BitmapFactory; 6 | import android.graphics.Canvas; 7 | import android.graphics.Matrix; 8 | import android.graphics.drawable.Drawable; 9 | import android.media.ExifInterface; 10 | import android.os.Build; 11 | import android.text.format.DateFormat; 12 | import android.util.Log; 13 | 14 | import java.io.File; 15 | import java.io.FileNotFoundException; 16 | import java.io.FileOutputStream; 17 | import java.io.IOException; 18 | import java.util.Calendar; 19 | import java.util.Locale; 20 | 21 | public class ImageUtil { 22 | 23 | public static String saveImage(Bitmap bitmap, String path) { 24 | 25 | String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".png"; 26 | FileOutputStream b = null; 27 | File file = new File(path); 28 | if (!file.exists()) { 29 | file.mkdirs();// 创建文件夹 30 | } 31 | String fileName = path + File.separator + name; 32 | try { 33 | b = new FileOutputStream(fileName); 34 | bitmap.compress(Bitmap.CompressFormat.JPEG, 75, b);// 把数据写入文件 35 | return fileName; 36 | } catch (FileNotFoundException e) { 37 | e.printStackTrace(); 38 | } finally { 39 | try { 40 | if (b != null) { 41 | b.flush(); 42 | b.close(); 43 | } 44 | } catch (IOException e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | return ""; 49 | } 50 | 51 | 52 | public static Bitmap getBitmap(Context context, int vectorDrawableId) { 53 | Bitmap bitmap; 54 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { 55 | Drawable vectorDrawable = context.getDrawable(vectorDrawableId); 56 | assert vectorDrawable != null; 57 | bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), 58 | vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 59 | Canvas canvas = new Canvas(bitmap); 60 | vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 61 | vectorDrawable.draw(canvas); 62 | } else { 63 | bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId); 64 | } 65 | return bitmap; 66 | } 67 | 68 | public static Bitmap zoomBitmap(Bitmap bm, int reqWidth, int reqHeight) { 69 | // 获得图片的宽高 70 | int width = bm.getWidth(); 71 | int height = bm.getHeight(); 72 | // 计算缩放比例 73 | float scaleWidth = ((float) reqWidth) / width; 74 | float scaleHeight = ((float) reqHeight) / height; 75 | float scale = Math.min(scaleWidth, scaleHeight); 76 | // 取得想要缩放的matrix参数 77 | Matrix matrix = new Matrix(); 78 | matrix.postScale(scale, scale); 79 | // 得到新的图片 80 | Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, 81 | true); 82 | return newbm; 83 | } 84 | 85 | /** 86 | * 根据计算的inSampleSize,得到压缩后图片 87 | * 88 | * @param pathName 路径 89 | * @param reqWidth 宽度 90 | * @param reqHeight 高度 91 | * @return 压缩后图片 92 | */ 93 | public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) { 94 | int degree = 0; 95 | try { 96 | ExifInterface exifInterface = new ExifInterface(pathName); 97 | int result = exifInterface.getAttributeInt( 98 | ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); 99 | switch (result) { 100 | case ExifInterface.ORIENTATION_ROTATE_90: 101 | degree = 90; 102 | break; 103 | case ExifInterface.ORIENTATION_ROTATE_180: 104 | degree = 180; 105 | break; 106 | case ExifInterface.ORIENTATION_ROTATE_270: 107 | degree = 270; 108 | break; 109 | } 110 | } catch (IOException e) { 111 | return null; 112 | } 113 | try { 114 | // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 115 | final BitmapFactory.Options options = new BitmapFactory.Options(); 116 | options.inJustDecodeBounds = true; 117 | BitmapFactory.decodeFile(pathName, options); 118 | // 调用上面定义的方法计算inSampleSize值 119 | options.inSampleSize = calculateInSampleSize(options, reqWidth, 120 | reqHeight); 121 | 122 | // 使用获取到的inSampleSize值再次解析图片 123 | options.inJustDecodeBounds = false; 124 | // options.inPreferredConfig = Bitmap.Config.RGB_565; 125 | Bitmap bitmap = BitmapFactory.decodeFile(pathName, options); 126 | 127 | if (degree != 0) { 128 | Bitmap newBitmap = rotateImageView(bitmap, degree); 129 | bitmap.recycle(); 130 | bitmap = null; 131 | return newBitmap; 132 | } 133 | 134 | return bitmap; 135 | } catch (OutOfMemoryError error) { 136 | Log.e("eee", "内存泄露!"); 137 | return null; 138 | } 139 | } 140 | 141 | /** 142 | * 旋转图片 143 | * 144 | * @param bitmap bitmap 145 | * @param angle 角度 146 | * @return 旋转过后的Bitmap 147 | */ 148 | public static Bitmap rotateImageView(Bitmap bitmap, int angle) { 149 | //旋转图片 动作 150 | Matrix matrix = new Matrix(); 151 | matrix.postRotate(angle); 152 | // 创建新的图片 153 | return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 154 | } 155 | 156 | /** 157 | * 计算inSampleSize,用于压缩图片 158 | * 159 | * @param options Options 160 | * @param reqWidth 宽度 161 | * @param reqHeight 高度 162 | * @return 压缩后的bitmap 163 | */ 164 | private static int calculateInSampleSize(BitmapFactory.Options options, 165 | int reqWidth, int reqHeight) { 166 | // 源图片的宽度 167 | int width = options.outWidth; 168 | int height = options.outHeight; 169 | int inSampleSize = 1; 170 | 171 | if (width > reqWidth && height > reqHeight) { 172 | // 计算出实际宽度和目标宽度的比率 173 | int widthRatio = Math.round((float) width / (float) reqWidth); 174 | int heightRatio = Math.round((float) height / (float) reqHeight); 175 | inSampleSize = Math.max(widthRatio, heightRatio); 176 | } 177 | return inSampleSize; 178 | } 179 | 180 | } -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/PermissionsConstant.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import android.Manifest; 4 | import android.os.Build; 5 | import android.support.annotation.RequiresApi; 6 | 7 | public class PermissionsConstant { 8 | 9 | public static final int REQUEST_CAMERA = 1; 10 | public static final int REQUEST_EXTERNAL_READ = 2; 11 | public static final int REQUEST_EXTERNAL_WRITE = 3; 12 | 13 | public static final String[] PERMISSIONS_CAMERA = { 14 | Manifest.permission.CAMERA, 15 | Manifest.permission.WRITE_EXTERNAL_STORAGE 16 | }; 17 | public static final String[] PERMISSIONS_EXTERNAL_WRITE = { 18 | Manifest.permission.WRITE_EXTERNAL_STORAGE 19 | }; 20 | 21 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) 22 | public static final String[] PERMISSIONS_EXTERNAL_READ = { 23 | Manifest.permission.READ_EXTERNAL_STORAGE 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/PermissionsUtils.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import android.app.Activity; 4 | import android.content.pm.PackageManager; 5 | import android.os.Build; 6 | import android.support.annotation.RequiresApi; 7 | import android.support.v4.app.ActivityCompat; 8 | import android.support.v4.content.ContextCompat; 9 | 10 | import static android.Manifest.permission.CAMERA; 11 | import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 12 | import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 13 | 14 | 15 | public class PermissionsUtils { 16 | 17 | public static boolean checkReadStoragePermission(Activity activity) { 18 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 19 | return true; 20 | } 21 | int readStoragePermissionState = 22 | ContextCompat.checkSelfPermission(activity, READ_EXTERNAL_STORAGE); 23 | 24 | boolean readStoragePermissionGranted = readStoragePermissionState == PackageManager.PERMISSION_GRANTED; 25 | 26 | if (!readStoragePermissionGranted) { 27 | ActivityCompat.requestPermissions(activity, 28 | PermissionsConstant.PERMISSIONS_EXTERNAL_READ, 29 | PermissionsConstant.REQUEST_EXTERNAL_READ); 30 | } 31 | return readStoragePermissionGranted; 32 | } 33 | 34 | @RequiresApi(api = Build.VERSION_CODES.M) 35 | public static boolean checkWriteStoragePermission(Activity activity) { 36 | 37 | int writeStoragePermissionState = 38 | ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE); 39 | 40 | boolean writeStoragePermissionGranted = writeStoragePermissionState == PackageManager.PERMISSION_GRANTED; 41 | 42 | if (!writeStoragePermissionGranted) { 43 | activity.requestPermissions(PermissionsConstant.PERMISSIONS_EXTERNAL_WRITE, 44 | PermissionsConstant.REQUEST_EXTERNAL_WRITE); 45 | } 46 | return writeStoragePermissionGranted; 47 | } 48 | 49 | @RequiresApi(api = Build.VERSION_CODES.M) 50 | public static boolean checkCameraPermission(Activity activity) { 51 | int cameraPermissionState = ContextCompat.checkSelfPermission(activity, CAMERA); 52 | 53 | boolean cameraPermissionGranted = cameraPermissionState == PackageManager.PERMISSION_GRANTED; 54 | 55 | if (!cameraPermissionGranted) { 56 | activity.requestPermissions(PermissionsConstant.PERMISSIONS_CAMERA, 57 | PermissionsConstant.REQUEST_CAMERA); 58 | } 59 | return cameraPermissionGranted; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/StatusBarUtils.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.graphics.Color; 7 | import android.os.Build; 8 | import android.support.annotation.ColorInt; 9 | import android.support.v7.widget.Toolbar; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.view.Window; 13 | import android.view.WindowManager; 14 | 15 | import java.lang.reflect.Field; 16 | 17 | 18 | public class StatusBarUtils { 19 | 20 | private static final int DEFAULT_STATUS_BAR_ALPHA = 0; 21 | 22 | /** 23 | * 设置状态栏颜色 24 | * 25 | * @param activity 需要设置的 activity 26 | * @param color 状态栏颜色值 27 | */ 28 | public static void setColor(Activity activity, @ColorInt int color) { 29 | setBarColor(activity, color); 30 | } 31 | 32 | /** 33 | * 设置状态栏背景色 34 | * 4.4以下不处理 35 | * 4.4使用默认沉浸式状态栏 36 | * 37 | * @param color 要为状态栏设置的颜色值 38 | */ 39 | public static void setBarColor(Activity activity, @ColorInt int color) { 40 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 41 | Window win = activity.getWindow(); 42 | View decorView = win.getDecorView(); 43 | win.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//沉浸式状态栏(4.4-5.0透明,5 44 | // .0以上半透明) 45 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//android5.0以上设置透明效果 46 | win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); 47 | //清除flag,为了android5.0以上也全透明效果 48 | //让应用的主体内容占用系统状态栏的空间 49 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 50 | | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; 51 | decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | option); 52 | win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 53 | win.setStatusBarColor(color);//设置状态栏背景色 54 | } 55 | } 56 | } 57 | 58 | /** 59 | * 设置状态栏全透明 60 | * 61 | * @param activity 需要设置的activity 62 | */ 63 | public static void setTransparent(Activity activity) { 64 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { 65 | return; 66 | } 67 | setColor(activity, Color.TRANSPARENT); 68 | } 69 | 70 | /** 71 | * 修正 Toolbar 的位置 72 | * 在 Android 4.4 版本下无法显示内容在 StatusBar 下,所以无需修正 Toolbar 的位置 73 | * 74 | * @param toolbar toolbar 75 | */ 76 | public static void fixToolbar(Toolbar toolbar, Activity activity) { 77 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 78 | int statusHeight = getStatusBarHeight(activity); 79 | ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) toolbar 80 | .getLayoutParams(); 81 | layoutParams.setMargins(0, statusHeight, 0, 0); 82 | } 83 | } 84 | 85 | /** 86 | * 修正 Titlebar 的位置 87 | * Fragment中android:fitsSystemWindows="true"属性无效时使用,直接在初始化的时候修改布局 88 | * 89 | * @param titlebar 自定义titlebar 布局 90 | */ 91 | public static void fixTitlebar(ViewGroup titlebar, Activity activity) { 92 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 93 | int statusHeight = getStatusBarHeight(activity); 94 | ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) titlebar 95 | .getLayoutParams(); 96 | layoutParams.setMargins(0, statusHeight, 0, 0); 97 | } 98 | } 99 | 100 | /** 101 | * 获取系统状态栏高度 102 | * 103 | * @param context context 104 | * @return 高度 105 | */ 106 | @SuppressLint("PrivateApi") 107 | public static int getStatusBarHeight(Context context) { 108 | Class c; 109 | Object obj; 110 | Field field; 111 | int x, statusBarHeight = 0; 112 | try { 113 | c = Class.forName("com.android.internal.R$dimen"); 114 | obj = c.newInstance(); 115 | field = c.getField("status_bar_height"); 116 | x = Integer.parseInt(field.get(obj).toString()); 117 | statusBarHeight = context.getResources().getDimensionPixelSize(x); 118 | } catch (Exception e1) { 119 | e1.printStackTrace(); 120 | } 121 | return statusBarHeight; 122 | } 123 | 124 | /** 125 | * 计算状态栏颜色 126 | * 127 | * @param color color值 128 | * @param alpha alpha值 129 | * @return 最终的状态栏颜色 130 | */ 131 | private static int calculateStatusColor(@ColorInt int color, int alpha) { 132 | float a = 1 - alpha / 255f; 133 | int red = color >> 16 & 0xff; 134 | int green = color >> 8 & 0xff; 135 | int blue = color & 0xff; 136 | red = (int) (red * a + 0.5); 137 | green = (int) (green * a + 0.5); 138 | blue = (int) (blue * a + 0.5); 139 | return 0xff << 24 | red << 16 | green << 8 | blue; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.utils; 2 | 3 | public class StringUtils { 4 | 5 | public static boolean isNotEmptyString(final String str) { 6 | return str != null && str.length() > 0; 7 | } 8 | 9 | public static boolean isEmptyString(final String str) { 10 | return str == null || str.length() <= 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/widget/AnimatorUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 GcsSloop 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Last modified 2017-03-31 03:42:28 17 | * 18 | * GitHub: https://github.com/GcsSloop 19 | * Website: http://www.gcssloop.com 20 | * Weibo: http://weibo.com/GcsSloop 21 | */ 22 | package com.winfo.photoselector.widget; 23 | 24 | import android.support.v4.view.ViewCompat; 25 | import android.support.v4.view.ViewPropertyAnimatorListener; 26 | import android.support.v4.view.animation.LinearOutSlowInInterpolator; 27 | import android.view.View; 28 | import android.view.animation.AccelerateInterpolator; 29 | 30 | public class AnimatorUtil { 31 | 32 | private static LinearOutSlowInInterpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new LinearOutSlowInInterpolator(); 33 | 34 | private static AccelerateInterpolator LINER_INTERPOLATOR = new AccelerateInterpolator(); 35 | 36 | 37 | // 显示view 38 | public static void scaleShow(View view, ViewPropertyAnimatorListener viewPropertyAnimatorListener) { 39 | view.setVisibility(View.VISIBLE); 40 | ViewCompat.animate(view) 41 | .scaleX(1.0f) 42 | .scaleY(1.0f) 43 | .alpha(1.0f) 44 | .setDuration(800) 45 | .setListener(viewPropertyAnimatorListener) 46 | .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR) 47 | .start(); 48 | } 49 | 50 | // 隐藏view 51 | public static void scaleHide(View view, ViewPropertyAnimatorListener viewPropertyAnimatorListener) { 52 | ViewCompat.animate(view) 53 | .scaleX(0.0f) 54 | .scaleY(0.0f) 55 | .alpha(0.0f) 56 | .setDuration(800) 57 | .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR) 58 | .setListener(viewPropertyAnimatorListener) 59 | .start(); 60 | } 61 | 62 | // 显示view 63 | public static void translateShow(View view, ViewPropertyAnimatorListener viewPropertyAnimatorListener) { 64 | view.setVisibility(View.VISIBLE); 65 | ViewCompat.animate(view) 66 | .translationY(0) 67 | .setDuration(400) 68 | .setListener(viewPropertyAnimatorListener) 69 | .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR) 70 | .start(); 71 | } 72 | 73 | // 隐藏view 74 | public static void translateHide(View view, ViewPropertyAnimatorListener viewPropertyAnimatorListener) { 75 | view.setVisibility(View.VISIBLE); 76 | ViewCompat.animate(view) 77 | .translationY(260) 78 | .setDuration(400) 79 | .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR) 80 | .setListener(viewPropertyAnimatorListener) 81 | .start(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/widget/MyViewPager.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.widget; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.ViewPager; 5 | import android.util.AttributeSet; 6 | import android.view.MotionEvent; 7 | 8 | /** 9 | * 继承ViewPager并在onInterceptTouchEvent捕捉异常。 10 | * 因为ViewPager嵌套PhotoView使用,有时候会发生IllegalArgumentException异常。 11 | */ 12 | public class MyViewPager extends ViewPager { 13 | 14 | public MyViewPager(Context context) { 15 | super(context); 16 | } 17 | 18 | public MyViewPager(Context context, AttributeSet attrs) { 19 | super(context, attrs); 20 | } 21 | 22 | @Override 23 | public boolean onInterceptTouchEvent(MotionEvent ev) { 24 | try { 25 | return super.onInterceptTouchEvent(ev); 26 | } catch (IllegalArgumentException e) { 27 | return false; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/widget/ScaleDownShowBehavior.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 GcsSloop 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * Last modified 2017-03-31 03:42:32 17 | * 18 | * GitHub: https://github.com/GcsSloop 19 | * Website: http://www.gcssloop.com 20 | * Weibo: http://weibo.com/GcsSloop 21 | */ 22 | 23 | package com.winfo.photoselector.widget; 24 | 25 | import android.content.Context; 26 | import android.support.annotation.NonNull; 27 | import android.support.design.widget.CoordinatorLayout; 28 | import android.support.v4.view.ViewCompat; 29 | import android.support.v4.view.ViewPropertyAnimatorListener; 30 | import android.util.AttributeSet; 31 | import android.view.View; 32 | 33 | 34 | @SuppressWarnings("unused") 35 | public class ScaleDownShowBehavior extends CoordinatorLayout.Behavior { 36 | 37 | public ScaleDownShowBehavior(Context context, AttributeSet attrs) { 38 | super(); 39 | } 40 | 41 | @Override 42 | public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { 43 | return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type); 44 | } 45 | 46 | @Override 47 | public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { 48 | if ((dyConsumed > 0 || dyUnconsumed > 0) && !isAnimateIng && isShow) {// 手指上滑,隐藏 49 | AnimatorUtil.translateHide(child, new StateListener() { 50 | @Override 51 | public void onAnimationStart(View view) { 52 | super.onAnimationStart(view); 53 | isShow = false; 54 | } 55 | }); 56 | } else if ((dyConsumed < 0 || dyUnconsumed < 0 && !isAnimateIng && !isShow)) { 57 | AnimatorUtil.translateShow(child, new StateListener() { 58 | @Override 59 | public void onAnimationStart(View view) { 60 | super.onAnimationStart(view); 61 | isShow = true; 62 | } 63 | });// 手指下滑,显示 64 | } 65 | } 66 | 67 | private boolean isAnimateIng = false; // 是否正在动画 68 | private boolean isShow = true; // 是否已经显示 69 | 70 | class StateListener implements ViewPropertyAnimatorListener { 71 | @Override 72 | public void onAnimationStart(View view) { 73 | isAnimateIng = true; 74 | } 75 | 76 | @Override 77 | public void onAnimationEnd(View view) { 78 | isAnimateIng = false; 79 | } 80 | 81 | @Override 82 | public void onAnimationCancel(View view) { 83 | isAnimateIng = false; 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /PhotoSelector/src/main/java/com/winfo/photoselector/widget/SquareImageView.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector.widget; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.AppCompatImageView; 5 | import android.util.AttributeSet; 6 | 7 | /** 8 | * 正方形的ImageView 9 | */ 10 | public class SquareImageView extends AppCompatImageView { 11 | 12 | public SquareImageView(Context context) { 13 | super(context); 14 | } 15 | 16 | public SquareImageView(Context context, AttributeSet attrs) { 17 | super(context, attrs); 18 | } 19 | 20 | public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) { 21 | super(context, attrs, defStyleAttr); 22 | } 23 | 24 | @Override 25 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 26 | super.onMeasure(widthMeasureSpec, widthMeasureSpec); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/anim/glide_anim.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/color/text_color.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable-xhdpi/text_indicator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wj576038874/PhotoSelector/2d5d258ee0e7231b919deed3fd58074dc409c691/PhotoSelector/src/main/res/drawable-xhdpi/text_indicator.png -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/border.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wj576038874/PhotoSelector/2d5d258ee0e7231b919deed3fd58074dc409c691/PhotoSelector/src/main/res/drawable/border.9.png -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/btn_back_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/btn_foreground_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/btn_green_shape.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/folder_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 11 | 12 | 13 | 14 | 15 | 20 | 21 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/ic_image.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/ic_image_select.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/ic_image_un_select.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/ic_img_load_fail.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/take_photo_normal.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/take_photo_press.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/drawable/toolbar_back.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 11 | 12 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/activity_image_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 12 | 13 | 24 | 25 | 36 | 37 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 68 | 69 | 82 | 83 | 84 | 92 | 93 | 94 | 109 | 110 | 118 | 119 | 124 | 125 | 131 | 132 | 139 | 140 | 149 | 150 | 151 | 152 | 153 | 154 | 160 | 161 | 172 | 173 | 174 | 175 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/activity_image_select2.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 13 | 14 | 24 | 25 | 36 | 37 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 62 | 63 | 72 | 84 | 85 | 86 | 87 | 93 | 94 | 107 | 108 | 114 | 115 | 120 | 121 | 127 | 128 | 135 | 136 | 145 | 146 | 147 | 148 | 149 | 150 | 156 | 157 | 168 | 169 | 170 | 171 | 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/activity_preview.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 19 | 20 | 25 | 26 | 31 | 32 | 33 | 34 | 41 | 42 | 51 | 52 | 60 | 61 | 75 | 76 | 77 | 78 | 79 | 80 | 87 | 88 | 101 | 102 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/activity_rv_preview.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 14 | 15 | 26 | 27 | 28 | 39 | 40 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 65 | 66 | 67 | 74 | 75 | 79 | 80 | 86 | 87 | 92 | 93 | 106 | 107 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/adapter_camera_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 14 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/adapter_folder.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 15 | 21 | 22 | 23 | 24 | 32 | 33 | 42 | 43 | 50 | 51 | 59 | 60 | 61 | 62 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/adapter_images_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 15 | 16 | 22 | 23 | 30 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/bootm_preview_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/bsd_folder_dialog.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/item_view_pager.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/layout/preview_item.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/values/color.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #BDBDBD 4 | #ffffff 5 | #3b7fd4 6 | -------------------------------------------------------------------------------- /PhotoSelector/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | PhotoSelector 3 | 图片 4 | 确定 5 | 预览 6 | 选择 7 | 全部图片 8 | 确定(%1$d/%2$d) 9 | 确定(%1$d) 10 | 预览(%1$d) 11 | com.winfo.photoselector.widget.ScaleDownShowBehavior 12 | 13 | -------------------------------------------------------------------------------- /PhotoSelector/src/test/java/com/winfo/photoselector/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselector; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PhotoSelector 2 | Android图片选择器,仿微信的图片选择器的样式和效果。可横竖屏切换显示, 3 | 自定义配置,单选,多选,是否显示拍照,material design风格,单选裁剪,拍照裁剪,滑动翻页预览,双击放大,缩放 4 | 5 | [kotlin版](https://github.com/wj576038874/PhotoSlectorKotlin) 6 | 7 | 效果图: [点击下载APK进行体验](https://raw.githubusercontent.com/wj576038874/PhotoSelectorDemo/master/apk/PhotoSelector.apk) 8 | 9 | ![相册](https://github.com/wj576038874/PhotoSelectorDemo/blob/master/images/selector.jpg) 10 | ![文件夹](https://github.com/wj576038874/PhotoSelectorDemo/blob/master/images/folder.jpg) 11 | ![预览](https://github.com/wj576038874/PhotoSelectorDemo/blob/master/images/preview.jpg) 12 | ![预览列表](https://github.com/wj576038874/PhotoSelectorDemo/blob/master/images/preview_list.jpg) 13 | ![裁剪](https://github.com/wj576038874/PhotoSelectorDemo/blob/master/images/clip.jpg) 14 | 15 | **1、引入依赖** 16 | 17 | 在工程的build.gradle添加如下配置 18 | ``` 19 | allprojects { 20 | repositories { 21 | google() 22 | jcenter() 23 | maven { url "https://jitpack.io" } 24 | } 25 | } 26 | ``` 27 | 28 | 在Module的build.gradle在添加以下代码 29 | 30 | ``` 31 | implementation 'com.winfo.photoselector:PhotoSelector:1.2.1' 32 | ``` 33 | 34 | 35 | **2、说明** 36 | 37 | PhotoSelector的图片加载是基于glide4.7.1实现的,可以自定义加载动画,预览照片使用 38 | **com.github.chrisbanes:PhotoView:2.1.3** 39 | 裁剪使用的是**com.github.yalantis:ucrop:2.2.2**等开源库,列表加载,翻页预览这里没有使用viewpager使用的是recycleview 40 | 41 | 42 | **3、使用** 43 | 44 | 在你的项目中的AndroidManifest文件中添加以下配置 45 | ``` 46 | 47 | 48 | 49 | 53 | 57 | 61 | 62 | 66 | ``` 67 | 68 | **3、调起图片选择器** 69 | 70 | 调用的是很简单,只需要一句代码,其他可选择性配置 71 | ```java 72 | //多选(最多9张) 73 | PhotoSelector.builder() 74 | .setShowCamera(true)//显示拍照 75 | .setMaxSelectCount(9)//最大选择9 默认9,如果这里设置为-1则是不限数量 76 | .setSelected(images)//已经选择的照片 77 | .setGridColumnCount(3)//列数 78 | .setMaterialDesign(true)//design风格 79 | .setToolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//toolbar的颜色 80 | .setBottomBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//底部bottombar的颜色 81 | .setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//状态栏的颜色 82 | .start(MainActivity.this, LIMIT_CODE);//当前activity 和 requestCode,不传requestCode则默认为PhotoSelector.DEFAULT_REQUEST_CODE 83 | 84 | //裁剪 85 | //单选后剪裁 裁剪的话都是针对一 86 | -------------------------------------------------------------------------------- /apk/PhotoSelector.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wj576038874/PhotoSelector/2d5d258ee0e7231b919deed3fd58074dc409c691/apk/PhotoSelector.apk -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 27 5 | defaultConfig { 6 | applicationId "com.winfo.photoselectordemo" 7 | minSdkVersion 15 8 | targetSdkVersion 27 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(include: ['*.jar'], dir: 'libs') 23 | implementation 'com.android.support:appcompat-v7:27.1.1' 24 | implementation 'com.android.support.constraint:constraint-layout:1.1.2' 25 | testImplementation 'junit:junit:4.12' 26 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 28 | implementation project(':PhotoSelector') 29 | // implementation 'com.winfo.photoselector:PhotoSelector:1.2.1' 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/winfo/photoselectordemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselectordemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.winfo.photoselectordemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 23 | 27 | 31 | 32 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/winfo/photoselectordemo/ImageAdapter.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselectordemo; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.support.v7.widget.RecyclerView; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.ImageView; 10 | 11 | import com.bumptech.glide.Glide; 12 | 13 | import java.io.File; 14 | import java.util.ArrayList; 15 | 16 | public class ImageAdapter extends RecyclerView.Adapter { 17 | 18 | private Context mContext; 19 | private ArrayList mImages; 20 | private LayoutInflater mInflater; 21 | 22 | ImageAdapter(Context context) { 23 | mContext = context; 24 | this.mInflater = LayoutInflater.from(mContext); 25 | } 26 | 27 | @NonNull 28 | @Override 29 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 30 | View view = mInflater.inflate(R.layout.adapter_image, parent, false); 31 | return new ViewHolder(view); 32 | } 33 | 34 | @Override 35 | public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { 36 | final String image = mImages.get(position); 37 | Glide.with(mContext).load(new File(image)).into(holder.ivImage); 38 | } 39 | 40 | @Override 41 | public int getItemCount() { 42 | return mImages == null ? 0 : mImages.size(); 43 | } 44 | 45 | public void refresh(ArrayList images) { 46 | mImages = images; 47 | notifyDataSetChanged(); 48 | } 49 | 50 | static class ViewHolder extends RecyclerView.ViewHolder { 51 | 52 | ImageView ivImage; 53 | 54 | ViewHolder(View itemView) { 55 | super(itemView); 56 | ivImage = itemView.findViewById(R.id.iv_image); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/winfo/photoselectordemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.winfo.photoselectordemo; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.net.Uri; 6 | import android.os.Bundle; 7 | import android.support.v4.content.ContextCompat; 8 | import android.support.v7.app.AppCompatActivity; 9 | import android.support.v7.widget.GridLayoutManager; 10 | import android.support.v7.widget.RecyclerView; 11 | import android.view.View; 12 | import android.widget.ImageView; 13 | 14 | import com.bumptech.glide.Glide; 15 | import com.winfo.photoselector.PhotoSelector; 16 | 17 | import java.util.ArrayList; 18 | 19 | public class MainActivity extends AppCompatActivity implements View.OnClickListener { 20 | 21 | private static final int SINGLE_CODE = 1;//单选 22 | private static final int LIMIT_CODE = 2;//多选限制数量 23 | private static final int CROP_CODE = 3;//剪切裁剪 24 | private static final int UN_LIMITT_CODE = 4;//多选不限制数量 25 | 26 | private ImageAdapter mAdapter; 27 | private ImageView imageView; 28 | 29 | @Override 30 | protected void onCreate(Bundle savedInstanceState) { 31 | super.onCreate(savedInstanceState); 32 | setContentView(R.layout.activity_main); 33 | imageView = findViewById(R.id.imageview); 34 | RecyclerView rvImage = findViewById(R.id.rv_image); 35 | rvImage.setLayoutManager(new GridLayoutManager(this, 3)); 36 | mAdapter = new ImageAdapter(this); 37 | rvImage.setAdapter(mAdapter); 38 | 39 | findViewById(R.id.btn_single).setOnClickListener(this); 40 | findViewById(R.id.btn_limit).setOnClickListener(this); 41 | findViewById(R.id.btn_unlimited).setOnClickListener(this); 42 | findViewById(R.id.btn_clip).setOnClickListener(this); 43 | } 44 | 45 | private ArrayList images; 46 | 47 | @Override 48 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 49 | super.onActivityResult(requestCode, resultCode, data); 50 | if (resultCode == Activity.RESULT_OK && data != null) { 51 | switch (requestCode) { 52 | case SINGLE_CODE: 53 | //单选的话 images就只有一条数据直接get(0)即可 54 | images = data.getStringArrayListExtra(PhotoSelector.SELECT_RESULT); 55 | mAdapter.refresh(images); 56 | break; 57 | case LIMIT_CODE: 58 | images = data.getStringArrayListExtra(PhotoSelector.SELECT_RESULT); 59 | mAdapter.refresh(images); 60 | break; 61 | case CROP_CODE: 62 | //获取到裁剪后的图片的Uri进行处理 63 | Uri resultUri = PhotoSelector.getCropImageUri(data); 64 | Glide.with(this).load(resultUri).into(imageView); 65 | break; 66 | case UN_LIMITT_CODE: 67 | images = data.getStringArrayListExtra(PhotoSelector.SELECT_RESULT); 68 | mAdapter.refresh(images); 69 | break; 70 | } 71 | } 72 | } 73 | 74 | @Override 75 | public void onClick(View v) { 76 | switch (v.getId()) { 77 | case R.id.btn_single: 78 | //单选 79 | PhotoSelector.builder() 80 | .setSingle(true) 81 | .start(MainActivity.this, SINGLE_CODE); 82 | break; 83 | 84 | case R.id.btn_limit: 85 | //多选(最多9张) 86 | PhotoSelector.builder() 87 | .setShowCamera(true)//显示拍照 88 | .setMaxSelectCount(9)//最大选择9 默认9,如果这里设置为-1则是不限数量 89 | .setSelected(images)//已经选择的照片 90 | .setGridColumnCount(3)//列数 91 | .setMaterialDesign(true)//design风格 92 | .setToolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//toolbar的颜色 93 | .setBottomBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//底部bottombar的颜色 94 | .setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//状态栏的颜色 95 | .start(MainActivity.this, LIMIT_CODE);//当前activity 和 requestCode,不传requestCode则默认为PhotoSelector.DEFAULT_REQUEST_CODE 96 | break; 97 | 98 | case R.id.btn_unlimited: 99 | //多选(不限数量) 100 | PhotoSelector.builder() 101 | .setMaxSelectCount(-1)//-1不限制数量 102 | .setSelected(images) 103 | .start(MainActivity.this, UN_LIMITT_CODE); 104 | break; 105 | 106 | case R.id.btn_clip: 107 | //单选后剪裁 裁剪的话都是针对一张图片所以要设置setSingle(true) 108 | PhotoSelector.builder() 109 | .setSingle(true)//单选,裁剪都是单选 110 | .setCrop(true)//是否裁剪 111 | .setCropMode(PhotoSelector.CROP_RECTANG)//设置裁剪模式 矩形还是圆形 112 | .setStatusBarColor(ContextCompat.getColor(this, R.color.colorAccent)) 113 | .setToolBarColor(ContextCompat.getColor(this, R.color.colorAccent)) 114 | .setBottomBarColor(ContextCompat.getColor(this, R.color.colorAccent)) 115 | .setStatusBarColor(ContextCompat.getColor(this, R.color.colorAccent)) 116 | .start(MainActivity.this, CROP_CODE); 117 | break; 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 19 | 20 |