├── .gitignore ├── .idea ├── codeStyles │ └── Project.xml ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── cn │ │ └── leo │ │ └── magicscreenadapter │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── cn │ │ │ └── leo │ │ │ └── magicscreenadapter │ │ │ ├── LeoRvAdapter.kt │ │ │ ├── MainActivity.kt │ │ │ ├── MyApplication.java │ │ │ ├── RvAdapter.kt │ │ │ ├── TestFragment.java │ │ │ └── TestV4Fragment.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── fragment_test.xml │ │ └── item_rv_test.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── cn │ └── leo │ └── magicscreenadapter │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screen_adapter_lib ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── cn │ │ └── leo │ │ └── magic │ │ └── screen │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── cn │ │ │ └── leo │ │ │ └── magic │ │ │ └── screen │ │ │ ├── IgnoreScreenAdapter.java │ │ │ ├── MagicScreenAdapter.java │ │ │ ├── ScreenAdapter.java │ │ │ ├── ScreenAdapterDesignWidthInDp.java │ │ │ └── ScreenAspect.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── cn │ └── leo │ └── magic │ └── screen │ └── ExampleUnitTest.java └── 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/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 | 10 | xmlns:android 11 | 12 | ^$ 13 | 14 | 15 | 16 |
17 |
18 | 19 | 20 | 21 | xmlns:.* 22 | 23 | ^$ 24 | 25 | 26 | BY_NAME 27 | 28 |
29 |
30 | 31 | 32 | 33 | .*:id 34 | 35 | http://schemas.android.com/apk/res/android 36 | 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | .*:name 45 | 46 | http://schemas.android.com/apk/res/android 47 | 48 | 49 | 50 |
51 |
52 | 53 | 54 | 55 | name 56 | 57 | ^$ 58 | 59 | 60 | 61 |
62 |
63 | 64 | 65 | 66 | style 67 | 68 | ^$ 69 | 70 | 71 | 72 |
73 |
74 | 75 | 76 | 77 | .* 78 | 79 | ^$ 80 | 81 | 82 | BY_NAME 83 | 84 |
85 |
86 | 87 | 88 | 89 | .* 90 | 91 | http://schemas.android.com/apk/res/android 92 | 93 | 94 | ANDROID_ATTRIBUTE_ORDER 95 | 96 |
97 |
98 | 99 | 100 | 101 | .* 102 | 103 | .* 104 | 105 | 106 | BY_NAME 107 | 108 |
109 |
110 |
111 |
112 |
113 |
-------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 36 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 41 | 42 | 43 | 44 | 45 | 46 | 48 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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 [2018] [Jarry Leo] 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MagicScreenAdapter 2 | **依赖本库**不用写一句代码做好屏幕适配: 3 | 4 | 本适配方案使用[今日头条的适配方案](https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA); 5 | 预览的时候建议使用(Nexus5,xxhdpi,1920x1080,360dp宽度)的屏幕分辨率预览; 6 | 7 | ### 布局预览是什么样在任何设备都是这个样子! 8 | 9 | ``` 10 | 本适配框架支持屏幕旋转,默认以设备最短边适配,要修改为最长边,在初始化的第二个参数选择 11 | MagicScreenAdapter.initDesignWidthInDp(1024,true); 12 | ``` 13 | *** 14 | 15 | ### 声明: 16 | **本框架以布局预览为标准,跟设计图无关** 17 | **您之前怎么把设计图转换成布局还是按照以前方式来** 18 | - 假设设计图尺寸720px,预览布局宽度360dp,假设一个控件100px宽度,在布局里写的就是100*360/720=50dp 19 | - 本适配方案支持固定尺寸适配,单位dp和sp都可以,px不行 20 | - 查看布局宽度dp方法:放一个控件进去,调整控件宽度直到刚好充满布局宽度,此时的控件宽度就是布局预览宽度 21 | 22 | 23 | > 如果老项目一直用的其它宽度dp预览的布局, 24 | > 则可以在Application 里面重设全局预览宽度(单位dp) 25 | > 这样可以快速适配老项目: 26 | ``` 27 | MagicScreenAdapter.initDesignWidthInDp(380); 28 | ``` 29 | 30 | ### 以下内容如果您的布局预览都是是统一的,请忽略! 31 | *** 32 | > 如果某个Activity 或者 Fragment 不想启用适配功能, 33 | > 请在类上使用注解:@IgnoreScreenAdapter; 34 | > 如果某个Activity 或者 Fragment 有单独的预览宽度(单位dp), 35 | > 请在类上使用注解:@ScreenAdapterDesignWidthInDp(400); 36 | > 如果一个Activity 同时展示多个Fragment ,并且Fragment之间 37 | > 或者 Fragment 和 Activity 之间的适配 宽度不一致,则 38 | > 会导致后续view的变化会以最后一个Fragment为准,解决方案: 39 | > view变化时,请用代码指定适配布局宽度: 40 | 41 | ``` 42 | MagicScreenAdapter.adapt(this, 360); //指定后续view变化的适配宽度 43 | MagicScreenAdapter.cancelAdapt(this);//或者后续view取消适配 44 | // this 为指定view 所在 Fragment 或者 Activity 45 | ``` 46 | *** 47 | ### 依赖方法: 48 | 49 | #### 1.在全局build里面添加下面github仓库地址 50 | ``` 51 | buildscript { 52 | ... 53 | dependencies { 54 | ... 55 | classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.6' 56 | } 57 | } 58 | allprojects { 59 | repositories { 60 | ... 61 | maven { url 'https://jitpack.io' } 62 | } 63 | } 64 | ``` 65 | > google()和jcenter()这两个仓库一般是默认的,如果没有请加上 66 | 67 | #### 2.在app的build里面添加插件和依赖 68 | ``` 69 | //如果是模块化开发,每个模块都要添加下面的插件 70 | apply plugin: 'android-aspectjx' 71 | ... 72 | dependencies { 73 | ... 74 | 75 | implementation 'com.github.jarryleo:MagicScreenAdapter:v2.8' 76 | //支持AndroidX版本用下面这个 77 | implementation 'com.github.jarryleo:MagicScreenAdapter:v2.1' 78 | } 79 | ``` 80 | *** 81 | > 上面2个build里面的 java 和 kotlin 二选一,如果AS版本低于3.0 请使用kotlin 版本 82 | > 用于支持kotlin的插件用的是 [aspectjx](https://github.com/HujiangTechnology/gradle_plugin_android_aspectjx) 83 | > 感谢原插件作者 84 | > 因为编织所有二进制文件的问题导致编译速度慢的问题,请查看原作者提供的解决方案 85 | > 部分代码来源:https://blankj.com/2018/07/30/easy-adapt-screen/?tdsourcetag=s_pctim_aiomsg 86 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android-extensions' 3 | apply plugin: 'kotlin-android' 4 | apply plugin: 'android-aspectjx' 5 | android { 6 | compileSdkVersion 27 7 | defaultConfig { 8 | applicationId "cn.leo.magicscreenadapter" 9 | minSdkVersion 16 10 | targetSdkVersion 27 11 | versionCode 1 12 | versionName "1.0" 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | } 15 | buildTypes { 16 | release { 17 | debuggable false 18 | minifyEnabled true 19 | zipAlignEnabled true 20 | shrinkResources true 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | debug { 24 | debuggable true 25 | minifyEnabled false 26 | zipAlignEnabled false 27 | shrinkResources false 28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 29 | } 30 | } 31 | } 32 | 33 | dependencies { 34 | implementation fileTree(include: ['*.jar'], dir: 'libs') 35 | implementation 'com.android.support:appcompat-v7:27.1.1' 36 | implementation 'com.android.support:recyclerview-v7:27.1.1' 37 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 38 | testImplementation 'junit:junit:4.12' 39 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 40 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 41 | implementation project(':screen_adapter_lib') 42 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 43 | // implementation 'com.github.jarryleo:MagicScreenAdapter:v1.7' 44 | } 45 | repositories { 46 | mavenCentral() 47 | } 48 | -------------------------------------------------------------------------------- /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/cn/leo/magicscreenadapter/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter; 2 | 3 | import android.content.Context; 4 | import androidx.test.platform.app.InstrumentationRegistry; 5 | import androidx.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 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/LeoRvAdapter.kt: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter 2 | 3 | import android.content.Context 4 | import android.os.Handler 5 | import android.os.Looper 6 | import android.support.annotation.* 7 | import android.support.v4.content.ContextCompat 8 | import android.support.v7.recyclerview.extensions.AsyncListDiffer 9 | import android.support.v7.util.DiffUtil 10 | import android.support.v7.widget.RecyclerView 11 | import android.support.v7.widget.RecyclerView.NO_POSITION 12 | import android.util.SparseArray 13 | import android.view.LayoutInflater 14 | import android.view.View 15 | import android.view.ViewGroup 16 | import android.widget.ImageView 17 | import android.widget.TextView 18 | import java.util.concurrent.Executor 19 | import java.util.concurrent.Executors 20 | 21 | @Suppress("UNUSED", "MemberVisibilityCanBePrivate") 22 | abstract class LeoRvAdapter : RecyclerView.Adapter() { 23 | 24 | /** 25 | * 列表赋值和取值 26 | */ 27 | open var data: List = listOf() 28 | get() = mDiffer.currentList 29 | set(value) { 30 | mLoadMoreCount = 0 31 | autoLoadMore = true 32 | field = value 33 | sMainThreadExecutor.execute { mDiffer.submitList(field) } 34 | } 35 | 36 | /** 37 | * 获取指定条目 38 | */ 39 | fun getItem(position: Int) = data[position] 40 | 41 | /** 42 | * 往列表尾部追加一条数据 43 | */ 44 | fun add(item: T) { 45 | data = data.toMutableList().apply { add(item) } 46 | } 47 | 48 | /** 49 | * 在列表末尾追加数据 50 | */ 51 | fun add(list: List) { 52 | data = data.toMutableList().apply { addAll(list) } 53 | } 54 | 55 | /** 56 | * 列表异步去重追加 57 | * 在列表末尾追加数据,并保证追加的数据不与原列表数据存在重复 58 | * 检查重复需要重写 {@link LeoRvAdapter#areItemsTheSame} 59 | * 和 {@link LeoRvAdapter#areContentsTheSame} 60 | */ 61 | fun addWithAsyncDistinct(list: List) { 62 | sDiffExecutor.execute { 63 | val oldList = data.toMutableList() 64 | var change = false 65 | //循环要添加的列表 66 | for (newItem in list) { 67 | //内容是否相同标识 68 | var contentSame = false 69 | for (i in oldList.indices) { 70 | val oldItem = oldList[i] 71 | //判断新旧条目是否相同 72 | if (!diffCallback.areItemsTheSame(oldItem, newItem)) { 73 | continue 74 | } 75 | //条目相同则判断内容是否相同 76 | contentSame = diffCallback.areContentsTheSame(oldItem, newItem) 77 | if (!contentSame) { 78 | //内容不同把新条目替换到老列表对应位置 79 | oldList[i] = newItem 80 | change = true 81 | contentSame = true 82 | } 83 | break 84 | } 85 | //内容不同则添加到老列表尾部 86 | if (!contentSame) { 87 | oldList.add(newItem) 88 | change = true 89 | } 90 | } 91 | //如果由新的内容加入则刷新列表显示 92 | if (change) { 93 | data = oldList 94 | } 95 | } 96 | } 97 | 98 | /** 99 | * 移除多个指定位置的条目 100 | */ 101 | fun remove(vararg position: Int) { 102 | val list = data.toMutableList() 103 | data = list.filterIndexed { index, _ -> 104 | !position.contains(index) 105 | } 106 | } 107 | 108 | /** 109 | * 移除列表内所有符合条件的条目 110 | */ 111 | inline fun remove(crossinline predicate: (T) -> Boolean) { 112 | data = data.toMutableList().apply { 113 | removeAll { predicate(it) } 114 | } 115 | } 116 | 117 | /** 118 | * 编辑单个数据 119 | */ 120 | fun edit(position: Int, call: (item: T) -> Unit) { 121 | call(data[position]) 122 | notifyItemChanged(position, javaClass.simpleName) 123 | } 124 | 125 | /** 126 | * 编辑符合条件的数据 127 | */ 128 | inline fun edit(predicate: (position: Int, item: T) -> Boolean, 129 | call: (position: Int, item: T) -> Unit) { 130 | data.forEachIndexed { index, t -> 131 | if (predicate(index, t)) { 132 | call(index, t) 133 | notifyItemChanged(index, javaClass.simpleName) 134 | } 135 | } 136 | } 137 | 138 | /** 139 | * 条目个数 140 | */ 141 | override fun getItemCount(): Int { 142 | return data.size 143 | } 144 | 145 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { 146 | return ViewHolder(parent, viewType) 147 | } 148 | 149 | override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { 150 | (holder as? LeoRvAdapter.ViewHolder)?.onBindViewHolder(position) 151 | } 152 | 153 | override fun getItemViewType(position: Int): Int { 154 | return getItemLayout(position) 155 | } 156 | 157 | /** 158 | * 局部刷新 159 | */ 160 | override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList) { 161 | if (payloads.isEmpty()) { 162 | onBindViewHolder(holder, position) 163 | } else { 164 | val viewHolder = holder as? LeoRvAdapter<*>.ViewHolder 165 | val helper = viewHolder?.itemHelper 166 | val itemHolder = helper?.mItemHolder 167 | val item = data[position] 168 | if (itemHolder != null) { 169 | itemHolder.bindData(helper, item) 170 | } else { 171 | onBindViewHolder(holder, position) 172 | } 173 | } 174 | } 175 | 176 | override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) { 177 | val viewHolder = holder as? LeoRvAdapter<*>.ViewHolder 178 | val helper = viewHolder?.itemHelper 179 | val itemHolder = helper?.mItemHolder 180 | itemHolder?.onViewDetach(helper) 181 | } 182 | 183 | /** 184 | * 获取条目类型的布局 185 | * 186 | * @param position 索引 187 | * @return 布局id 188 | */ 189 | @LayoutRes 190 | protected abstract fun getItemLayout(position: Int): Int 191 | 192 | /** 193 | * 给条目绑定数据 194 | * 195 | * @param helper 条目帮助类 196 | * @param data 对应数据 197 | */ 198 | protected abstract fun bindData(helper: ItemHelper, data: T) 199 | 200 | private val diffCallback = object : DiffUtil.ItemCallback() { 201 | 202 | override fun areItemsTheSame(oldItem: T, newItem: T): Boolean { 203 | return this@LeoRvAdapter.areItemsTheSame(oldItem, newItem) 204 | } 205 | 206 | override fun areContentsTheSame(oldItem: T, newItem: T): Boolean { 207 | return this@LeoRvAdapter.areContentsTheSame(oldItem, newItem) 208 | } 209 | } 210 | 211 | private val mDiffer: AsyncListDiffer = AsyncListDiffer(this, diffCallback) 212 | 213 | /** 214 | * 判断两个条目是否相同,相同则检查内容,用于局部刷新 215 | */ 216 | open fun areItemsTheSame(oldItem: T, newItem: T): Boolean { 217 | return oldItem.hashCode() == newItem.hashCode() 218 | } 219 | 220 | /** 221 | * 判断两个条目内容是否相同,如果两个条目相同内容不同,则会刷新对应位置数据 222 | */ 223 | open fun areContentsTheSame(oldItem: T, newItem: T): Boolean { 224 | return oldItem == newItem 225 | } 226 | 227 | inner class ViewHolder internal constructor(parent: ViewGroup, layout: Int) : 228 | RecyclerView.ViewHolder(LayoutInflater.from(parent.context) 229 | .inflate(layout, parent, false)), 230 | View.OnClickListener, 231 | View.OnLongClickListener { 232 | val itemHelper: ItemHelper = ItemHelper(this) 233 | 234 | init { 235 | itemHelper.setLayoutResId(layout) 236 | itemHelper.setOnItemChildClickListener(mOnItemChildClickListenerProxy) 237 | itemHelper.setRVAdapter(this@LeoRvAdapter) 238 | itemView.setOnClickListener(this) 239 | itemView.setOnLongClickListener(this) 240 | } 241 | 242 | var mPosition = 0 243 | get() { 244 | if (field != adapterPosition){ 245 | if (adapterPosition != NO_POSITION) { 246 | mPosition = adapterPosition 247 | return adapterPosition 248 | } 249 | } 250 | return field 251 | } 252 | 253 | fun onBindViewHolder(position: Int) { 254 | mPosition = position 255 | bindData(itemHelper, data[mPosition]) 256 | loadMore(mPosition) 257 | } 258 | 259 | override fun onClick(v: View) { 260 | if (::mOnItemClickListener.isInitialized) { 261 | mOnItemClickListener(this@LeoRvAdapter, v, mPosition) 262 | } 263 | } 264 | 265 | override fun onLongClick(v: View): Boolean { 266 | if (::mOnItemLongClickListener.isInitialized) { 267 | mOnItemLongClickListener(this@LeoRvAdapter, v, mPosition) 268 | return true 269 | } 270 | return false 271 | } 272 | } 273 | 274 | private fun loadMore(position: Int) { 275 | if (::mOnLoadMoreListener.isInitialized && 276 | autoLoadMore && 277 | mLoadMoreCount != itemCount && 278 | position == itemCount - 1) { 279 | mLoadMoreCount = itemCount 280 | mOnLoadMoreListener(this@LeoRvAdapter, itemCount - 1) 281 | } 282 | } 283 | 284 | class ItemHelper(private val viewHolder: LeoRvAdapter.ViewHolder) : View.OnClickListener { 285 | private val viewCache = SparseArray() 286 | private val clickListenerCache = ArrayList() 287 | private val mTags = HashMap() 288 | lateinit var adapter: LeoRvAdapter 289 | private set 290 | @LayoutRes 291 | @get:LayoutRes 292 | var itemLayoutResId: Int = 0 293 | val position 294 | get() = viewHolder.mPosition 295 | val itemView: View = viewHolder.itemView 296 | val context: Context = itemView.context 297 | var tag: Any? = null 298 | 299 | private lateinit var mOnItemChildClickListener: 300 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit 301 | 302 | fun setLayoutResId(@LayoutRes layoutResId: Int) { 303 | this.itemLayoutResId = layoutResId 304 | } 305 | 306 | fun setOnItemChildClickListener(onItemChildClickListener: 307 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit) { 308 | mOnItemChildClickListener = onItemChildClickListener 309 | } 310 | 311 | fun setRVAdapter(RVAdapter: LeoRvAdapter) { 312 | adapter = RVAdapter 313 | } 314 | 315 | fun setTag(key: String, tag: Any) { 316 | mTags[key] = tag 317 | } 318 | 319 | fun getTag(key: String): Any? { 320 | return mTags[key] 321 | } 322 | 323 | @Suppress("UNCHECKED_CAST") 324 | fun findViewById(@IdRes viewId: Int): V { 325 | val v = viewCache.get(viewId) 326 | val view: V? 327 | if (v == null) { 328 | view = itemView.findViewById(viewId) 329 | if (view == null) { 330 | val entryName = itemView.resources.getResourceEntryName(viewId) 331 | throw NullPointerException("id: R.id.$entryName can not find in this item!") 332 | } 333 | viewCache.put(viewId, view) 334 | } else { 335 | view = v as V 336 | } 337 | return view 338 | } 339 | 340 | fun getViewById(@IdRes viewId: Int, call: (V) -> Unit = {}): ItemHelper { 341 | val view = findViewById(viewId) 342 | call(view) 343 | return this 344 | } 345 | 346 | /** 347 | * 给按钮或文本框设置文字 348 | * 349 | * @param viewId 控件id 350 | * @param text 设置的文字 351 | */ 352 | fun setText(@IdRes viewId: Int, text: CharSequence?): ItemHelper { 353 | getViewById(viewId) { 354 | if (it is TextView) { 355 | it.text = text 356 | } else { 357 | val entryName = it.resources.getResourceEntryName(viewId) 358 | throw ClassCastException("id: R.id.$entryName are not TextView") 359 | } 360 | } 361 | return this 362 | } 363 | 364 | /** 365 | * 给按钮或文本框设置文字 366 | * 367 | * @param viewId 控件id 368 | * @param resId 设置的文字资源 369 | */ 370 | fun setText(@IdRes viewId: Int, @StringRes resId: Int): ItemHelper { 371 | getViewById(viewId) { 372 | if (it is TextView) { 373 | it.text = try { 374 | it.resources.getString(resId) 375 | } catch (e: Exception) { 376 | resId.toString() 377 | } 378 | } else { 379 | val entryName = it.resources.getResourceEntryName(viewId) 380 | throw ClassCastException("id: R.id.$entryName are not TextView") 381 | } 382 | } 383 | return this 384 | } 385 | 386 | /** 387 | * 设置文本颜色 388 | * 389 | * @param viewId 要设置文本的控件,TextView及其子类都可以 390 | * @param color 颜色int值,不是资源Id 391 | */ 392 | fun setTextColor(@IdRes viewId: Int, @ColorInt color: Int): ItemHelper { 393 | getViewById(viewId) { 394 | if (it is TextView) { 395 | it.setTextColor(color) 396 | } else { 397 | val entryName = it.resources.getResourceEntryName(viewId) 398 | throw ClassCastException("id: R.id.$entryName are not TextView") 399 | } 400 | } 401 | return this 402 | } 403 | 404 | /** 405 | * 设置文本颜色 406 | * 407 | * @param viewId 要设置文本的控件,TextView及其子类都可以 408 | * @param colorResId 颜色资源Id 409 | */ 410 | fun setTextColorRes(@IdRes viewId: Int, @ColorRes colorResId: Int): ItemHelper { 411 | getViewById(viewId) { 412 | if (it is TextView) { 413 | it.setTextColor(ContextCompat.getColor(it.context,colorResId)) 414 | } else { 415 | val entryName = it.resources.getResourceEntryName(viewId) 416 | throw ClassCastException("id: R.id.$entryName are not TextView") 417 | } 418 | } 419 | return this 420 | } 421 | 422 | /** 423 | * 给图片控件设置资源图片 424 | * 425 | * @param viewId 图片控件id 426 | * @param resId 资源id 427 | */ 428 | fun setImageResource(@IdRes viewId: Int, @DrawableRes resId: Int): ItemHelper { 429 | getViewById(viewId) { 430 | if (it is ImageView) { 431 | it.setImageResource(resId) 432 | } else { 433 | val entryName = it.resources.getResourceEntryName(viewId) 434 | throw ClassCastException("id: R.id.$entryName are not ImageView") 435 | } 436 | } 437 | return this 438 | } 439 | 440 | /** 441 | * 设置view的背景 442 | * 443 | * @param viewId 控件id 444 | * @param resId 资源id 445 | */ 446 | fun setBackgroundResource(@IdRes viewId: Int, @DrawableRes resId: Int): ItemHelper { 447 | getViewById(viewId) { 448 | it.setBackgroundResource(resId) 449 | } 450 | return this 451 | } 452 | 453 | fun setVisibility(@IdRes viewId: Int, visibility: Int): ItemHelper { 454 | getViewById(viewId) { 455 | it.visibility = visibility 456 | } 457 | return this 458 | } 459 | 460 | fun setVisibleOrGone(@IdRes viewId: Int, visibility: () -> Boolean): ItemHelper { 461 | getViewById(viewId) { 462 | it.visibility = if (visibility()) { 463 | View.VISIBLE 464 | } else { 465 | View.GONE 466 | } 467 | } 468 | return this 469 | } 470 | 471 | fun setVisibleOrInVisible(@IdRes viewId: Int, visibility: () -> Boolean): ItemHelper { 472 | getViewById(viewId) { 473 | it.visibility = if (visibility()) { 474 | View.VISIBLE 475 | } else { 476 | View.INVISIBLE 477 | } 478 | } 479 | return this 480 | } 481 | 482 | fun setViewVisible(@IdRes vararg viewId: Int): ItemHelper { 483 | for (id in viewId) { 484 | getViewById(id) { 485 | it.visibility = View.VISIBLE 486 | } 487 | } 488 | return this 489 | } 490 | 491 | fun setViewInvisible(@IdRes vararg viewId: Int): ItemHelper { 492 | for (id in viewId) { 493 | getViewById(id) { 494 | it.visibility = View.INVISIBLE 495 | } 496 | } 497 | return this 498 | } 499 | 500 | fun setViewGone(@IdRes vararg viewId: Int): ItemHelper { 501 | for (id in viewId) { 502 | getViewById(id) { 503 | it.visibility = View.GONE 504 | } 505 | } 506 | return this 507 | } 508 | 509 | /** 510 | * 给条目中的view添加点击事件 511 | * 512 | * @param viewId 控件id 513 | */ 514 | fun addOnClickListener(@IdRes viewId: Int): ItemHelper { 515 | val contains = clickListenerCache.contains(viewId) 516 | if (!contains) { 517 | getViewById(viewId) { it.setOnClickListener(this) } 518 | clickListenerCache.add(viewId) 519 | } 520 | return this 521 | } 522 | 523 | override fun onClick(v: View) { 524 | if (::mOnItemChildClickListener.isInitialized) { 525 | mOnItemChildClickListener(adapter, v, position) 526 | } 527 | } 528 | 529 | var mItemHolder: ItemHolder? = null 530 | @Suppress("UNCHECKED_CAST") 531 | fun setItemHolder(itemHolderClass: Class>) { 532 | try { 533 | if (mItemHolder == null) { 534 | val newInstance = itemHolderClass.newInstance() 535 | mItemHolder = newInstance as ItemHolder? 536 | mItemHolder?.initView(this, adapter.data[position]) 537 | } 538 | mItemHolder?.bindData(this, adapter.data[position]) 539 | } catch (e: InstantiationException) { 540 | e.printStackTrace() 541 | } catch (e: IllegalAccessException) { 542 | e.printStackTrace() 543 | } 544 | 545 | } 546 | } 547 | 548 | 549 | /** 550 | * 多条目类型防止 adapter臃肿,每个条目请继承此类 551 | * 552 | * @param 数据类型 553 | */ 554 | abstract class ItemHolder { 555 | 556 | /** 557 | * 绑定数据 558 | * 559 | * @param helper 帮助类 560 | * @param item 数据 561 | */ 562 | abstract fun bindData(helper: ItemHelper, item: T) 563 | 564 | /** 565 | * 初始化view,只在view第一次创建调用 566 | * 567 | * @param helper 帮助类 568 | * @param item 数据 569 | */ 570 | open fun initView(helper: ItemHelper, item: T) {} 571 | 572 | 573 | /** 574 | * 被回收时调用,用来释放一些资源,或者重置数据等 575 | * 576 | * @param helper 帮助类 577 | */ 578 | open fun onViewDetach(helper: ItemHelper) { 579 | 580 | } 581 | } 582 | 583 | private lateinit var mOnLoadMoreListener: 584 | (adapter: LeoRvAdapter, lastItemPosition: Int) -> Unit 585 | private lateinit var mOnItemClickListener: 586 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit 587 | private lateinit var mOnItemLongClickListener: 588 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit 589 | private lateinit var mOnItemChildClickListener: 590 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit 591 | val mOnItemChildClickListenerProxy: 592 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit = 593 | { adapter, v, position -> 594 | if (::mOnItemChildClickListener.isInitialized) { 595 | mOnItemChildClickListener(adapter, v, position) 596 | } 597 | } 598 | 599 | var autoLoadMore = true 600 | private var mLoadMoreCount = 0 601 | 602 | fun setOnItemClickListener(onItemClickListener: 603 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit) { 604 | mOnItemClickListener = onItemClickListener 605 | } 606 | 607 | fun setLoadMoreListener(onLoadMoreListener: 608 | (adapter: LeoRvAdapter, lastItemPosition: Int) -> Unit) { 609 | mOnLoadMoreListener = onLoadMoreListener 610 | } 611 | 612 | fun setOnItemLongClickListener(onItemLongClickListener: 613 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit) { 614 | mOnItemLongClickListener = onItemLongClickListener 615 | } 616 | 617 | fun setOnItemChildClickListener(onItemChildClickListener: 618 | (adapter: LeoRvAdapter, v: View, position: Int) -> Unit) { 619 | mOnItemChildClickListener = onItemChildClickListener 620 | } 621 | 622 | private class MainThreadExecutor : Executor { 623 | internal val mHandler = Handler(Looper.getMainLooper()) 624 | 625 | override fun execute(command: Runnable) { 626 | mHandler.post(command) 627 | } 628 | } 629 | 630 | companion object { 631 | private val sDiffExecutor = Executors.newFixedThreadPool(2) 632 | private val sMainThreadExecutor = MainThreadExecutor() 633 | } 634 | } -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import android.support.v7.widget.LinearLayoutManager 6 | import kotlinx.android.synthetic.main.activity_main.* 7 | 8 | /** 9 | * @author Leo 10 | */ 11 | class MainActivity : AppCompatActivity() { 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | setContentView(R.layout.activity_main) 16 | addFragment() 17 | initRecyclerView() 18 | } 19 | 20 | private fun addFragment() { 21 | val fm = supportFragmentManager 22 | fm.beginTransaction() 23 | .replace(R.id.container, TestV4Fragment()) 24 | .commitAllowingStateLoss() 25 | } 26 | 27 | private fun initRecyclerView() { 28 | rv1.layoutManager = LinearLayoutManager(this) 29 | val rvAdapter = RvAdapter() 30 | rv1.adapter = rvAdapter 31 | rvAdapter.data = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/MyApplication.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter; 2 | 3 | import android.app.Application; 4 | 5 | import cn.leo.magic.screen.MagicScreenAdapter; 6 | 7 | /** 8 | * @author : Jarry Leo 9 | * @date : 2018/8/31 15:29 10 | */ 11 | public class MyApplication extends Application { 12 | @Override 13 | public void onCreate() { 14 | super.onCreate(); 15 | MagicScreenAdapter.initDesignWidthInDp(360,false); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/RvAdapter.kt: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter 2 | 3 | /** 4 | * @author : ling luo 5 | * @date : 2019-09-25 6 | */ 7 | class RvAdapter : LeoRvAdapter() { 8 | 9 | override fun getItemLayout(position: Int): Int { 10 | return R.layout.item_rv_test 11 | } 12 | 13 | override fun bindData(helper: ItemHelper, data: Int) { 14 | helper.setText(R.id.tvTest,data.toString()) 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/TestFragment.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter; 2 | 3 | import android.app.Fragment; 4 | import android.os.Bundle; 5 | 6 | import android.support.annotation.Nullable; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | /** 12 | * @author : Jarry Leo 13 | * @date : 2018/10/11 9:30 14 | */ 15 | public class TestFragment extends Fragment { 16 | @Override 17 | public void onCreate(@Nullable Bundle savedInstanceState) { 18 | super.onCreate(savedInstanceState); 19 | } 20 | 21 | @Nullable 22 | @Override 23 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { 24 | return inflater.inflate(R.layout.fragment_test, null); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/cn/leo/magicscreenadapter/TestV4Fragment.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.support.v4.app.Fragment; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | 12 | 13 | /** 14 | * @author : Jarry Leo 15 | * @date : 2018/10/11 9:30 16 | */ 17 | public class TestV4Fragment extends Fragment { 18 | @Override 19 | public void onCreate(@Nullable Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | } 22 | 23 | @Nullable 24 | @Override 25 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 26 | return inflater.inflate(R.layout.fragment_test, null); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /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 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 20 | 21 | 31 | 32 | 37 | 38 | 43 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 20 | 21 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_rv_test.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | magic 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/cn/leo/magicscreenadapter/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magicscreenadapter; 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 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.50' 5 | 6 | repositories { 7 | google() 8 | jcenter() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.5.0' 12 | classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.6' 13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 14 | 15 | // NOTE: Do not place your application dependencies here; they belong 16 | // in the individual module build.gradle files 17 | } 18 | } 19 | 20 | allprojects { 21 | repositories { 22 | google() 23 | jcenter() 24 | maven { url 'https://jitpack.io' } 25 | } 26 | } 27 | 28 | task clean(type: Delete) { 29 | delete rootProject.buildDir 30 | } 31 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jarryleo/MagicScreenAdapter/3aa20755059141f34657e97c1daf90a1f76b9537/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Sep 26 15:02:58 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /screen_adapter_lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /screen_adapter_lib/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'android-aspectjx' 3 | 4 | android { 5 | compileSdkVersion 27 6 | defaultConfig { 7 | minSdkVersion 16 8 | } 9 | } 10 | 11 | dependencies { 12 | compileOnly 'com.android.support:appcompat-v7:27.1.1' 13 | compileOnly 'com.android.support:recyclerview-v7:27.1.1' 14 | } 15 | -------------------------------------------------------------------------------- /screen_adapter_lib/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 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/androidTest/java/cn/leo/magic/screen/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import android.content.Context; 4 | import androidx.test.platform.app.InstrumentationRegistry; 5 | import androidx.test.ext.junit.runners.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("cn.leo.magic.screen.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/java/cn/leo/magic/screen/IgnoreScreenAdapter.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author : Jarry Leo 10 | * @date : 2018/8/31 15:10 11 | */ 12 | @Target(ElementType.TYPE) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface IgnoreScreenAdapter { 15 | } 16 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/java/cn/leo/magic/screen/MagicScreenAdapter.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import android.app.Activity; 4 | import android.app.Fragment; 5 | import android.support.annotation.NonNull; 6 | import android.support.v4.app.FragmentActivity; 7 | 8 | /** 9 | * @author : Jarry Leo 10 | * @date : 2018/8/31 15:20 11 | */ 12 | public class MagicScreenAdapter { 13 | 14 | private MagicScreenAdapter() { 15 | } 16 | 17 | public static void initDesignWidthInDp(int designWidthInDp) { 18 | ScreenAdapter.mGlobalDesignWidthInDp = designWidthInDp; 19 | } 20 | 21 | public static void initDesignWidthInDp(int designWidthInDp,boolean isAdaptLongSide) { 22 | ScreenAdapter.mGlobalDesignWidthInDp = designWidthInDp; 23 | ScreenAdapter.mIsAdaptLongSide = isAdaptLongSide; 24 | } 25 | 26 | public static void adapt(@NonNull Activity activity) { 27 | adapt(activity, 0); 28 | } 29 | 30 | public static void adapt(@NonNull Fragment fragment) { 31 | adapt(fragment.getActivity(), 0); 32 | } 33 | 34 | public static void adapt(@NonNull android.support.v4.app.Fragment fragment) { 35 | FragmentActivity activity = fragment.getActivity(); 36 | if (activity != null) { 37 | adapt(activity, 0); 38 | } 39 | } 40 | 41 | public static void adapt(@NonNull Activity activity, int designWidthInDp) { 42 | ScreenAdapter.adaptScreen(activity, designWidthInDp); 43 | } 44 | 45 | public static void adapt(@NonNull Fragment fragment, int designWidthInDp) { 46 | adapt(fragment.getActivity(), designWidthInDp); 47 | } 48 | 49 | public static void adapt(@NonNull android.support.v4.app.Fragment fragment, int designWidthInDp) { 50 | FragmentActivity activity = fragment.getActivity(); 51 | if (activity != null) { 52 | adapt(fragment.getActivity(), designWidthInDp); 53 | } 54 | } 55 | 56 | public static void cancelAdapt(@NonNull Activity activity) { 57 | boolean isAdapt = ScreenAdapter.isAdaptScreen(activity); 58 | if (isAdapt) { 59 | ScreenAdapter.cancelAdaptScreen(activity); 60 | } 61 | } 62 | 63 | public static void cancelAdapt(@NonNull Fragment fragment) { 64 | cancelAdapt(fragment.getActivity()); 65 | } 66 | 67 | public static void cancelAdapt(@NonNull android.support.v4.app.Fragment fragment) { 68 | FragmentActivity activity = fragment.getActivity(); 69 | if (activity != null) { 70 | cancelAdapt(fragment.getActivity()); 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/java/cn/leo/magic/screen/ScreenAdapter.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import android.app.Activity; 4 | import android.content.res.Configuration; 5 | import android.content.res.Resources; 6 | import android.util.DisplayMetrics; 7 | 8 | /** 9 | * @author : Jarry Leo 10 | * @date : 2018/8/31 14:02 11 | */ 12 | class ScreenAdapter { 13 | /** 14 | * 默认全局预览布局宽度 15 | */ 16 | static int mGlobalDesignWidthInDp = 360; 17 | 18 | static boolean mIsAdaptLongSide = false; 19 | 20 | 21 | /** 22 | * Reference from: https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA 23 | */ 24 | static void adaptScreen(final Activity activity, int designWidthInDp) { 25 | if (activity == null) { 26 | return; 27 | } 28 | if (designWidthInDp <= 0) { 29 | designWidthInDp = mGlobalDesignWidthInDp; 30 | } 31 | final DisplayMetrics systemDm = Resources.getSystem().getDisplayMetrics(); 32 | final DisplayMetrics appDm = activity.getApplication().getResources().getDisplayMetrics(); 33 | final DisplayMetrics activityDm = activity.getResources().getDisplayMetrics(); 34 | boolean isVerticalSlide = (activity.getResources().getConfiguration().orientation 35 | == Configuration.ORIENTATION_PORTRAIT); 36 | int width = activityDm.widthPixels; 37 | int height = activityDm.heightPixels; 38 | int longSide = Math.max(width, height); 39 | 40 | if (mIsAdaptLongSide) { 41 | activityDm.density = longSide / (float) designWidthInDp; 42 | } else { 43 | if (isVerticalSlide) { 44 | activityDm.density = activityDm.widthPixels / (float) designWidthInDp; 45 | } else { 46 | activityDm.density = activityDm.heightPixels / (float) designWidthInDp; 47 | } 48 | } 49 | activityDm.scaledDensity = activityDm.density * (systemDm.scaledDensity / systemDm.density); 50 | activityDm.densityDpi = (int) (160 * activityDm.density + 0.5); 51 | appDm.density = activityDm.density; 52 | appDm.scaledDensity = activityDm.scaledDensity; 53 | appDm.densityDpi = activityDm.densityDpi; 54 | } 55 | 56 | /** 57 | * Cancel adapt the screen. 58 | * 59 | * @param activity The activity. 60 | */ 61 | static void cancelAdaptScreen(final Activity activity) { 62 | if (activity == null) { 63 | return; 64 | } 65 | final DisplayMetrics systemDm = Resources.getSystem().getDisplayMetrics(); 66 | final DisplayMetrics appDm = activity.getApplication().getResources().getDisplayMetrics(); 67 | final DisplayMetrics activityDm = activity.getResources().getDisplayMetrics(); 68 | activityDm.density = systemDm.density; 69 | activityDm.scaledDensity = systemDm.scaledDensity; 70 | activityDm.densityDpi = systemDm.densityDpi; 71 | appDm.density = systemDm.density; 72 | appDm.scaledDensity = systemDm.scaledDensity; 73 | appDm.densityDpi = systemDm.densityDpi; 74 | } 75 | 76 | /** 77 | * Return whether adapt screen. 78 | * 79 | * @return {@code true}: yes
{@code false}: no 80 | */ 81 | static boolean isAdaptScreen(Activity activity) { 82 | if (activity == null) { 83 | return false; 84 | } 85 | final DisplayMetrics systemDm = Resources.getSystem().getDisplayMetrics(); 86 | final DisplayMetrics appDm = activity.getApplication().getResources().getDisplayMetrics(); 87 | return systemDm.density != appDm.density; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/java/cn/leo/magic/screen/ScreenAdapterDesignWidthInDp.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @author : Jarry Leo 10 | * @date : 2018/8/31 15:10 11 | */ 12 | @Target(ElementType.TYPE) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | public @interface ScreenAdapterDesignWidthInDp { 15 | int value() default 360; 16 | } 17 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/java/cn/leo/magic/screen/ScreenAspect.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 2 | 3 | import android.app.Activity; 4 | import android.app.Fragment; 5 | import android.content.Context; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.util.Log; 8 | import android.view.ViewGroup; 9 | 10 | import org.aspectj.lang.JoinPoint; 11 | import org.aspectj.lang.annotation.Aspect; 12 | import org.aspectj.lang.annotation.Before; 13 | import org.aspectj.lang.annotation.Pointcut; 14 | 15 | /** 16 | * @author : Jarry Leo 17 | * @date : 2018/8/31 13:59 18 | */ 19 | 20 | @Aspect 21 | public class ScreenAspect { 22 | @Pointcut("execution(* android.app.Activity+.onCreate(..))") 23 | public void pointcutActivityOnCreate() { 24 | 25 | } 26 | 27 | @Pointcut("execution(* android.app.Activity+.onResume(..))") 28 | public void pointcutActivityOnResume() { 29 | 30 | } 31 | 32 | @Pointcut("execution(* android.app.Fragment+.onCreate(..))") 33 | public void pointcutFragmentOnCreate() { 34 | 35 | } 36 | 37 | @Pointcut("execution(* android.app.Fragment+.onResume(..))") 38 | public void pointcutFragmentOnResume() { 39 | 40 | } 41 | 42 | @Pointcut("execution(* android.support.v4.app.Fragment+.onCreate(..))") 43 | public void pointcutFragmentV4OnCreate() { 44 | 45 | } 46 | 47 | @Pointcut("execution(* android.support.v4.app.Fragment+.onResume(..))") 48 | public void pointcutFragmentV4OnResume() { 49 | 50 | } 51 | 52 | @Pointcut("execution(* android.support.v7.widget.RecyclerView.Adapter+.onCreateViewHolder(..))") 53 | public void pointcutRecyclerView() { 54 | 55 | } 56 | 57 | 58 | @Before("pointcutActivityOnCreate() || pointcutActivityOnResume() || " + 59 | "pointcutFragmentOnCreate() || pointcutFragmentOnResume() || " + 60 | "pointcutFragmentV4OnCreate() || pointcutFragmentV4OnResume() || pointcutRecyclerView()") 61 | public void before(JoinPoint joinPoint) throws Throwable { 62 | Object target = joinPoint.getTarget(); 63 | boolean hasIgnoreAdapter = target.getClass().isAnnotationPresent(IgnoreScreenAdapter.class); 64 | boolean hasDesignWidth = target.getClass().isAnnotationPresent(ScreenAdapterDesignWidthInDp.class); 65 | int designWidthInDp = ScreenAdapter.mGlobalDesignWidthInDp; 66 | if (hasDesignWidth) { 67 | ScreenAdapterDesignWidthInDp annotation = 68 | target.getClass().getAnnotation(ScreenAdapterDesignWidthInDp.class); 69 | designWidthInDp = annotation.value(); 70 | } 71 | if (target instanceof Activity) { 72 | if (hasIgnoreAdapter) { 73 | ScreenAdapter.cancelAdaptScreen((Activity) target); 74 | } else { 75 | ScreenAdapter.adaptScreen((Activity) target, designWidthInDp); 76 | } 77 | } else if (target instanceof Fragment) { 78 | if (hasIgnoreAdapter) { 79 | ScreenAdapter.cancelAdaptScreen(((Fragment) target).getActivity()); 80 | } else { 81 | ScreenAdapter.adaptScreen(((Fragment) target).getActivity(), designWidthInDp); 82 | } 83 | } else if (target instanceof android.support.v4.app.Fragment) { 84 | if (hasIgnoreAdapter) { 85 | ScreenAdapter.cancelAdaptScreen(((android.support.v4.app.Fragment) target).getActivity()); 86 | } else { 87 | ScreenAdapter.adaptScreen(((android.support.v4.app.Fragment) target).getActivity(), designWidthInDp); 88 | } 89 | } else if (target instanceof RecyclerView.Adapter) { 90 | Object[] args = joinPoint.getArgs(); 91 | if (args[0] instanceof ViewGroup) { 92 | ViewGroup viewGroup = (ViewGroup) args[0]; 93 | Context context = viewGroup.getContext(); 94 | if (context instanceof Activity) { 95 | if (hasIgnoreAdapter) { 96 | ScreenAdapter.cancelAdaptScreen((Activity) context); 97 | } else { 98 | ScreenAdapter.adaptScreen((Activity) context, designWidthInDp); 99 | } 100 | } 101 | } 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /screen_adapter_lib/src/test/java/cn/leo/magic/screen/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package cn.leo.magic.screen; 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 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':screen_adapter_lib' 2 | --------------------------------------------------------------------------------