├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── mvvm │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── mvvm │ │ │ ├── MvvmApplication.java │ │ │ ├── adapter │ │ │ ├── BaseAdapter.java │ │ │ ├── ContributorAdapter.java │ │ │ └── SearchAdapter.java │ │ │ ├── event │ │ │ └── UserFollowEvent.java │ │ │ ├── exception │ │ │ ├── AccessDenyException.java │ │ │ ├── ConversionException.java │ │ │ ├── NetworkException.java │ │ │ ├── Non200HttpException.java │ │ │ └── UnKnowException.java │ │ │ ├── http │ │ │ ├── ApiServiceFactory.java │ │ │ ├── ApiServiceFactory2.java │ │ │ ├── ErrorCallAdapterFactory.java │ │ │ ├── GitHubApi.java │ │ │ ├── NetErrorType.java │ │ │ ├── SearchApi.java │ │ │ └── SynchronousCallAdapterFactory.java │ │ │ ├── model │ │ │ ├── AuthToken.java │ │ │ ├── Book.java │ │ │ ├── Contributor.java │ │ │ ├── User.java │ │ │ └── UserField.java │ │ │ ├── ui │ │ │ ├── BaseActivity.java │ │ │ ├── ConverterActivity.java │ │ │ ├── CustomSetterActivity.java │ │ │ ├── DataBindSimpleActivity.java │ │ │ ├── ELActivity.java │ │ │ ├── GitHubContributorsActivity.java │ │ │ ├── LoadingDialog.java │ │ │ ├── MainActivity.java │ │ │ ├── SearchDebounceActivity.java │ │ │ └── UpdateUserActivity.java │ │ │ └── utils │ │ │ ├── CrashHandler.java │ │ │ ├── DividerItemDecoration.java │ │ │ └── RecyclerViewUtils.java │ └── res │ │ ├── drawable-xxhdpi │ │ ├── erorr_loading.png │ │ ├── ic_like_yellow.png │ │ └── ic_like_yellowfull.png │ │ ├── drawable │ │ ├── placeholder_small_image.xml │ │ ├── progress_medium_holo.xml │ │ └── shape_toast_bg.xml │ │ ├── layout │ │ ├── activity_converter.xml │ │ ├── activity_custom_setter.xml │ │ ├── activity_el.xml │ │ ├── activity_github_contributors.xml │ │ ├── activity_main.xml │ │ ├── activity_observable.xml │ │ ├── activity_search_debounce.xml │ │ ├── activity_simple.xml │ │ ├── activity_update_user.xml │ │ ├── dialog_common_loading.xml │ │ ├── footer_loading_layout.xml │ │ ├── item_contributor.xml │ │ ├── item_search.xml │ │ └── item_unknown.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ ├── spinner_48_inner_holo.png │ │ └── spinner_48_outer_holo.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── mvvm │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # Log Files 26 | *.log 27 | 28 | # Android Studio Navigation editor temp files 29 | .navigation/ 30 | 31 | # Android Studio captures folder 32 | captures/ 33 | 34 | .idea/ 35 | 36 | *.iml 37 | 38 | *.iml 39 | 40 | *.iml 41 | 42 | *.iml 43 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 项目整体效果: 4 | ![这里写图片描述](http://img.blog.csdn.net/20160305155616553) 5 | 6 | 7 | 8 | # Awesome-Android-MVVM 9 | - 什么是MVVM, 为什么需要 MVVM? 10 | - 如何在android中使用DataBinding实现MVVM架构? 11 | 12 | ## 什么是MVVM , 为什么需要MVVM? 13 | 14 | MVVM是Model-View-ViewModel的简写. 它是有三个部分组成:Model、View、ViewModel。 15 | 16 | Model:数据模型层。包含业务逻辑和校验逻辑。 17 | 18 | View:屏幕上显示的UI界面(layout、views)。 19 | 20 | ViewModel:View和Model之间的链接桥梁,处理视图逻辑。 21 | 22 | MVVM功能图如下: 23 | 24 | ![Alt text](https://cdn-images-1.medium.com/max/800/1*VLhXURHL9rGlxNYe9ydqVg.png "MVVM Image") 25 | 26 | MVVM架构通过ViewModel隔离了UI层和业务逻辑层,降低程序的耦合度。 27 | 28 | ### Android App 中MVC的不足 29 | 一般来说,我们开发Android App是基于MVC,由于MVC的普及和快速开发的特点,一个app从0开发一般都是基于MVC的。 30 | 31 | Activity、Fragment相当于C (Controller), 布局相当于V(View), 数据层相当于M(Model) 32 | 33 | 随着业务的增长,Controller里的代码会越来越臃肿,因为它不只要负责业务逻辑,还要控制View的展示。也就是说Activity、Fragment杂糅了Controller和View,耦合变大。并不能算作真正意义上的MVC。 34 | 35 | 编写代码基本的过程是这样的,在Activity、Fragment中初始化Views,然后拉取数据,成功后把数据填充到View里。 36 | 37 | `假如有如下场景`: 38 | 39 | > 我们基于MVC开发完第一版本,然后企业需要迭代2.0版本,并且UI界面变化比较大,业务变动较小,怎么办呢? 40 | 当2.0的所有东西都已经评审过后。这个时候,新建布局,然后开始按照新的效果图,进行UI布局。然后还要新建Activity、Fragment把相关逻辑和数据填充到新的View上。 41 | 如果业务逻辑比较复杂,需要从Activity、Fragment中提取上个版本的所有逻辑,这个时候自己可能就要晕倒了,因为一个复杂的业务,一个Activity几千行代码也是很常见的。千辛万苦做完提取完,可能还会出现很多bug。 42 | 43 | 一开始我尝试使用MVP架构, MVP功能图如下: 44 | 45 | ![Alt text](http://rocko-blog.qiniudn.com/Android%E4%B8%AD%E7%9A%84MVP_1.png "MVP Image") 46 | 47 | 48 | 49 | MVP 把视图层抽象到View接口,逻辑层抽象到 Presenter 接口,提到了代码的可读性。降低了视图逻辑和业务逻辑的耦合。 50 | 51 | 但是有 MVP 的不足: 52 | 53 | 1. 接口过多,一定程度影响了编码效率。 54 | 2. 业务逻辑抽抽象到Presenter中,较为复杂的界面Activity代码量依然会很多。 55 | 3. 导致Presenter的代码量过大。 56 | 57 | 58 | 这个时候MVVM就闪亮登场了。从上面的MVVM功能图我们知道: 59 | 60 | 1. 可重用性。你可以把一些视图逻辑放在一个ViewModel里面,让很多view重用这段视图逻辑。 61 | 在Android中,布局里可以进行一个视图逻辑,并且Model发生变化,View也随着发生变化。 62 | 2. 低耦合。以前Activity、Fragment中需要把数据填充到View,还要进行一些视图逻辑。现在这些都可在布局中完成(具体代码请看后面) 63 | 甚至都不需要再Activity、Fragment去findViewById。这时候Activity、Fragment只需要做好的逻辑处理就可以了。 64 | 65 | 66 | 现在我们回到上面从app1.0到app2.0迭代的问题,如果用MVVM去实现那就比较简单,这个时候不需要动Activity、Fragment, 67 | 只需要把布局按照2.0版本的效果实现一遍即可。因为视图逻辑和数据填充已经在布局里了,这就是上面提到的可重用性。 68 | 69 | > 发展过程: 70 | MVC->MVP->MVVP 71 | 72 | 73 | ## Android中如何实现MVVM架构? 74 | Google在2015年的已经为我们DataBinding技术。下面就详细讲解如何使用DataBinding。 75 | 76 | ### 1,环境准备 77 | 在工程根目录build.gradle文件加入如下配置,把Android Gradle 插件升级到最新: 78 | 79 | dependencies { 80 | classpath 'com.android.tools.build:gradle:1.5.0' 81 | } 82 | 83 | 84 | 85 | 在app里的build.gradle文件加入如下配置,启用data binding 功能: 86 | 87 | 88 | dataBinding { 89 | enabled true 90 | } 91 | 92 | 93 | 94 | ### 2,来个简单的例子 95 | 96 | 实现上面效果的“Data Binding Simple Sample” 97 | 98 | #### data binding 布局格式和以往的有些区别: 99 | 100 | ``` 101 | 102 | 103 | 104 | 105 | 106 | 107 | //normal layout 108 | 111 | 112 | ``` 113 | 114 | 115 | - 布局的根节点为 116 | 117 | - 布局里使用的model 通过中的指定: 118 | 119 | ``` 120 | 121 | 122 | ``` 123 | 124 | - 设置空间属性的值,通过@{}语法来设置: 125 | 126 | ``` 127 | android:text="@{user.firstName}" 128 | 129 | ``` 130 | 131 | 下面是完整的布局实现: 132 | 133 | ``` 134 | 135 | 136 | 137 | 138 | 139 | 142 | 143 | 144 | 151 | 152 | 153 | 158 | 159 | 165 | 166 | 167 | 172 | 173 | 180 | 181 | 187 | 188 | 194 | 195 | 202 | 203 | 204 | 205 | 206 | 212 | 213 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | ``` 227 | 228 | 229 | 230 | ####接下来实现数据模型类User: 231 | 232 | ``` 233 | public class User { 234 | 235 | private String userName; 236 | private String realName; 237 | private String mobile; 238 | private int age; 239 | 240 | public User(String realName, String mobile) { 241 | this.realName = realName; 242 | this.mobile = mobile; 243 | } 244 | 245 | public User() { 246 | } 247 | 248 | //ignore getter and setter. see code for detail. 249 | 250 | } 251 | 252 | ``` 253 | 254 | #### 在Activity中 绑定数据 255 | 256 | ``` 257 | @Override 258 | public void onCreate(Bundle savedInstanceState) { 259 | super.onCreate(savedInstanceState); 260 | binding = DataBindingUtil.setContentView(this, R.layout.activity_simple); 261 | fetchData(); 262 | } 263 | 264 | //模拟获取数据 265 | private void fetchData() { 266 | new AsyncTask() { 267 | 268 | @Override 269 | protected void onPreExecute() { 270 | super.onPreExecute(); 271 | showLoadingDialog(); 272 | } 273 | 274 | @Override 275 | protected Void doInBackground(Void... params) { 276 | try { 277 | Thread.sleep(2000); 278 | } catch (InterruptedException e) { 279 | e.printStackTrace(); 280 | } 281 | return null; 282 | } 283 | 284 | @Override 285 | protected void onPostExecute(Void aVoid) { 286 | super.onPostExecute(aVoid); 287 | hideLoadingDialog(); 288 | User user = new User("Chiclaim", "13512341234"); 289 | binding.setUser(user); 290 | //binding.setVariable(com.mvvm.BR.user, user); 291 | } 292 | }.execute(); 293 | } 294 | } 295 | 296 | ``` 297 | 298 | 299 | > 通过DataBindingUtil.setContentView设置布局,通过binding类设置数据模型: 300 | 301 | ``` 302 | binding.setUser(user); 303 | ``` 304 | 305 | 306 | ### 3,布局详解 307 | 308 | #### import导入 309 | - 通过标签导入: 310 | 311 | ``` 312 | 313 | 314 | 315 | 316 | 317 | android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}" 318 | ``` 319 | 320 | - 如果产生了冲突可以使用别名的方式: 321 | 322 | ``` 323 | 324 | 325 | 326 | 327 | ``` 328 | 329 | - 集合泛型左尖括号需要使用转译: 330 | 331 | ``` 332 | 333 | 334 | 335 | 336 | 337 | ``` 338 | 339 | - 使用导入类的静态字段和方法: 340 | 341 | ``` 342 | 343 | 344 | 345 | 346 | … 347 | 351 | 352 | ``` 353 | 354 | > 像JAVA一样,java.lang.*是自动导入的。 355 | 356 | 357 | 358 | #### Variables 359 | 在节点中使用来设置。 360 | 361 | ``` 362 | 363 | 364 | 365 | 366 | 367 | ``` 368 | 369 | - Binding类里将会包含通过variable设置name的getter和setter方法。如上面的setUser,getUser等。 370 | 371 | - 如果控件设置了id,那么该控件也可以在binding类中找到,这样就不需要findViewById来获取View了。 372 | 373 | #### 自定义Binding类名(Custom Binding Class Names) 374 | 375 | 以为根节点布局,android studio默认会自动产生一个Binding类。类名为根据布局名产生,如一个名为activity_simple的布局,它的Binding类为ActivitySimpleBinding,所在包为app_package/databinding。 376 | 当然也可以自定义Binding类的名称和包名: 377 | 378 | 1. `` 在app_package/databinding下生成CustomBinding; 379 | 380 | 2. `` 在app_package下生成CustomBinding; 381 | 382 | 3. `` 明确指定包名和类名。 383 | 384 | 385 | 386 | #### Includes 387 | ``` 388 | 389 | 391 | 392 | 393 | 394 | 398 | 400 | 402 | 403 | 404 | 405 | ``` 406 | 407 | name.xml 和 contact.xml都必须包含 ` ` 408 | 409 | ### 4,DataBinding Obervable 410 | 411 | 在上面的一个例子上,数据是不变,随着用户的与app的交互,数据发生了变化,如何更新某个控件的值呢? 412 | 413 | 有如下几种方案(具体实现下载代码,运行,点击DataBinding Observable 按钮): 414 | 415 | 1. BaseObservable的方式 416 | 417 | 使User继承BaseObservable,在get方法上加上注解@Bindable,会在BR(BR类自动生成的)生成该字段标识(int) 418 | set方法里notifyPropertyChanged(BR.field); 419 | 420 | ``` 421 | public class User extends BaseObservable{ 422 | 423 | private String userName; 424 | private String realName; 425 | 426 | /** 427 | * 注意: 在BR里对应的常量为follow 428 | */ 429 | private boolean isFollow; 430 | 431 | 432 | public User(String realName, String mobile) { 433 | this.realName = realName; 434 | this.mobile = mobile; 435 | } 436 | 437 | public User() { 438 | } 439 | 440 | @Bindable 441 | public boolean isFollow() { 442 | return isFollow; 443 | } 444 | 445 | public void setIsFollow(boolean isFollow) { 446 | this.isFollow = isFollow; 447 | notifyPropertyChanged(BR.follow); 448 | } 449 | 450 | @Bindable 451 | public String getUserName() { 452 | return userName; 453 | } 454 | 455 | public void setUserName(String userName) { 456 | this.userName = userName; 457 | notifyPropertyChanged(BR.userName); 458 | } 459 | ``` 460 | 461 | > 如果数据发生变化通过set方法,view的值会自动更新,是不是很方便。 462 | 463 | 464 | 2. 通过ObserableField来实现 465 | 466 | ``` 467 | public class UserField { 468 | public final ObservableField realName = new ObservableField<>(); 469 | public final ObservableField mobile = new ObservableField<>(); 470 | 471 | } 472 | 473 | ``` 474 | 475 | 布局中使用: 476 | 477 | ``` 478 | 479 | 480 | 486 | 487 | ``` 488 | 489 | 代码中设置/改变数据: 490 | 491 | ``` 492 | userField.realName.set("Chiclaim"); 493 | 494 | ``` 495 | 496 | 3. Observable Collections方式: 497 | 498 | ``` 499 | private ObservableArrayMap map = new ObservableArrayMap(); 500 | 501 | //设置数据 502 | map.put("realName", "Chiclaim"); 503 | map.put("mobile", "110"); 504 | 505 | 506 | ``` 507 | 508 | 布局中使用: 509 | 510 | ``` 511 | 518 | 519 | ``` 520 | 521 | ### 5,下面通过DataBinding来实现列表 522 | 523 | 获取square公司retrofit代码贡献者数据列表,通过RecyclerView来实现。 524 | RecyclerView的Adapter实现的核心方法为两个onCreateViewHolder、onBindViewHolder方法和Item的ViewHolder。 525 | 526 | ``` 527 | @Override 528 | public RecyclerView.ViewHolder onMyCreateViewHolder(ViewGroup parent, int viewType) { 529 | ItemContributorBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_contributor, parent, false); 530 | ContributorViewHolder viewHolder = new ContributorViewHolder(binding.getRoot()); 531 | viewHolder.setBinding(binding); 532 | return viewHolder; 533 | } 534 | 535 | @Override 536 | public void onMyBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { 537 | ContributorViewHolder contributorViewHolder = (ContributorViewHolder) viewHolder; 538 | Contributor contributor = getModel(position); 539 | contributorViewHolder.getBinding().setVariable(com.mvvm.BR.contributor, contributor); 540 | contributorViewHolder.getBinding().executePendingBindings(); 541 | Picasso.with(mContext).load(contributor.getAvatar_url()). 542 | into(contributorViewHolder.binding.ivAvatar); 543 | } 544 | 545 | 546 | ``` 547 | 548 | 通过setVariable方法来关联数据。 549 | getBinding().setVariable(com.mvvm.BR.contributor, contributor) 550 | 大家看到BR.contributor的contributor常量是怎么产生的?布局里的中的name属性值。如: 那么就会自动生成BR.book。`有点类似以前的R里面的id`。 有人会问了如果别的实体(model)也有相同的book属性怎么办?那他到底使用哪个呢?其实这是不会冲突,因为在不用的地方用,他的上下文(Binging)不一样,所以不会冲突。也是和以前的R里面的常量是一回事情。只是把它放到BR里面去了。所以我猜想BR的全称应该是(`Binding R`(R就是以前我们用的常量类))虽然官方没有说明。 551 | 552 | 通过 executePendingBindings 强制执行绑定数据。 553 | 554 | Item对应的VIewHolder 555 | 556 | ``` 557 | public class ContributorViewHolder extends RecyclerView.ViewHolder { 558 | 559 | ItemContributorBinding binding; 560 | 561 | public void setBinding(ItemContributorBinding binding) { 562 | this.binding = binding; 563 | } 564 | 565 | public ItemContributorBinding getBinding() { 566 | return binding; 567 | } 568 | 569 | public ContributorViewHolder(View itemView) { 570 | super(itemView); 571 | } 572 | } 573 | 574 | 575 | ``` 576 | 577 | > 在实现这个列表功能我使用了Retrofit+RxJava来做的。在这里引入了token机制,也就是说每个请求都会去把token带过去,然后服务器验证token是否过期,如果过期服务器就会返回403(没有访问权限),这个时候就需要去请求新的Token,然后再去请求列表数据(目前我在服务器端是设置了10s过期,服务器端代码也放在github上【[github地址](https://github.com/chiclaim/android_mvvm_server)】。 578 | > 假如不使用RxJava实现这样的嵌套逻辑请求就比较复杂了,如果过期,发起获取新Token的请求,成功去请求列表数据,这种嵌套的回调,可读性、可维护性很差。并且只要有请求的地方都需要加上这样的逻辑,当然普通的方式可以实现,只是不够优雅而已。使用RxJava就很优雅了,具体如何实现请查看代码。RxJava功能很强大,以后会通过单独的文章来进行说明。 579 | 580 | 581 | 582 | 583 | ### 6,EL 表达式(Expression Language) 584 | 585 | ####DataBinding支持的表达式有: 586 | 587 | 数学表达式: + - / * % 588 | 589 | 字符串拼接 + 590 | 591 | 逻辑表达式 && || 592 | 593 | 位操作符 & | ^ 594 | 595 | 一元操作符 + - ! ~ 596 | 597 | 位移操作符 >> >>> << 598 | 599 | 比较操作符 == > < >= <= 600 | 601 | instanceof 602 | 603 | 分组操作符 () 604 | 605 | 字面量 - character, String, numeric, null 606 | 607 | 强转、方法调用 608 | 609 | 字段访问 610 | 611 | 数组访问 [] 612 | 613 | 三元操作符 ?: 614 | 615 | #### 聚合判断(Null Coalescing Operator)语法 ‘??’ 616 | 622 | 623 | 上面的意思是如果userName为null,则显示realName。 624 | 625 | #### Resource(资源相关) 626 | 在DataBinding语法中,可以吧resource作为其中的一部分。如: 627 | 628 | ``` 629 | android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}" 630 | 631 | ``` 632 | 633 | 除了支持dimen,还支持color、string、drawable、anim等。 634 | 635 | 注意,对mipmap图片资源支持还是有问题,目前只支持drawable。 636 | 637 | #### Event Binding (事件绑定) 638 | 639 | 事件处理器: 640 | 641 | ``` 642 | public interface UserFollowEvent { 643 | void follow(View view); 644 | void unFollow(View view); 645 | } 646 | 647 | ``` 648 | 649 | 布局中使用: 650 | 651 | ``` 652 | 655 | 656 | android:onClick="@{user.isFollow ? event.unFollow : event.follow}" 657 | ``` 658 | 659 | 在 Activity 实现该接口 UserFollowEvent : 660 | 661 | ``` 662 | @Override 663 | public void follow(View view) { 664 | user.setIsFollow(true); 665 | } 666 | 667 | @Override 668 | public void unFollow(View view) { 669 | user.setIsFollow(false); 670 | } 671 | ``` 672 | 673 | 效果如下所示: 674 | 675 | ![Alt text](http://img.blog.csdn.net/20160227112258647 "关注前") 676 | 677 | 点击按钮后: 678 | 679 | ![Alt text](http://img.blog.csdn.net/20160227112357012 "点击按钮后") 680 | 681 | 682 | ### Custom Setter(自定义Setter方法) 683 | 有些时候我们需要自定义binding逻辑,如:在一个TextView上设置大小不一样的文字,这个时候就需要我们自定义binding逻辑了. 684 | 685 | 在比如我们为ImageView加载图片,通过总是通过类似这样的的代码来实现: 686 | 687 | ``` 688 | Picasso.with(view.getContext()).load(url).into(view); 689 | ``` 690 | 如果我们自定Setter方法,那么这些都可以是自动的。怎么实现呢? 691 | 692 | ``` 693 | @BindingAdapter({"imageUrl"}) 694 | public static void loadImage(ImageView view, String url) { 695 | Log.d("BindingAdapter", "loadImage(ImageView view, String url)"); 696 | Log.d("BindingAdapter", url + ""); 697 | Picasso.with(view.getContext()).load(url).into(view); 698 | } 699 | ``` 700 | @BindingAdapter({"imageUrl"}) 这句话意味着我们自顶一个imageUrl属性,可以在布局文件中使用。当在布局文件中设置该属性的值发生改变,会自动 701 | 调用loadImage(ImageView view, String url)方法。 702 | 703 | 布局中使用: 704 | 705 | ``` 706 | 711 | ``` 712 | 713 | 再来看下如何实现:在一个TextView上设置大小不一样的文字(其实是一样的) 714 | 715 | ``` 716 | @BindingAdapter("spanText") 717 | public static void setText(TextView textView, String value) { 718 | Log.d("BindingAdapter", "setText(TextView textView,String value)"); 719 | SpannableString styledText = new SpannableString(value); 720 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style0), 721 | 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 722 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style1), 723 | 5, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 724 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style0), 725 | 12, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 726 | textView.setText(styledText, TextView.BufferType.SPANNABLE); 727 | } 728 | ``` 729 | 730 | ``` 731 | 735 | ``` 736 | 737 | 注意:使用自定义Setter,需要使用dataBinding语法。以下用法是不对的: 738 | 739 | ``` 740 | 744 | ``` 745 | 746 | > 其他的例子就不一一在这里介绍了,详情可以查看github上的代码。 747 | 748 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 30 5 | buildToolsVersion "29.0.3" 6 | 7 | dataBinding { 8 | enabled true 9 | } 10 | 11 | 12 | defaultConfig { 13 | applicationId "com.mvvm" 14 | minSdkVersion 15 15 | targetSdkVersion 30 16 | versionCode 1 17 | versionName "1.0" 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | } 26 | 27 | repositories { 28 | 29 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 30 | 31 | } 32 | 33 | dependencies { 34 | compile fileTree(dir: 'libs', include: ['*.jar']) 35 | 36 | testImplementation 'junit:junit:4.12' 37 | implementation 'androidx.appcompat:appcompat:1.2.0' 38 | implementation 'androidx.recyclerview:recyclerview:1.1.0' 39 | 40 | //http module 41 | //snapshot worked with okhttp3.0.1 42 | //compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' 43 | //compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' 44 | //compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta4' 45 | 46 | //compile 'com.squareup.retrofit2:retrofit:2.0.0-SNAPSHOT' 47 | //compile 'com.squareup.retrofit2:converter-gson:2.0.0-SNAPSHOT' 48 | //compile 'com.squareup.retrofit2:retrofit-converters:2.0.0-SNAPSHOT' 49 | 50 | implementation 'com.squareup.retrofit:retrofit:1.9.0' 51 | implementation 'com.squareup.retrofit:retrofit-converters:1.9.0' 52 | 53 | implementation 'com.squareup.okhttp3:okhttp:4.9.0' 54 | implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.0.1' 55 | implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0' 56 | 57 | //image utils 58 | implementation 'com.squareup.picasso:picasso:2.5.2' 59 | 60 | //RxJava 61 | implementation 'io.reactivex:rxandroid:1.2.1' 62 | implementation 'io.reactivex:rxjava:1.3.0' 63 | implementation 'io.reactivex:rxjava-math:1.0.0' 64 | implementation 'com.jakewharton.rxbinding:rxbinding:1.0.0' 65 | 66 | } 67 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/yuzhiqiang/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/mvvm/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.mvvm; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 28 | 29 | 33 | 34 | 38 | 39 | 43 | 44 | 48 | 49 | 53 | 54 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/MvvmApplication.java: -------------------------------------------------------------------------------- 1 | package com.mvvm; 2 | 3 | import android.app.Application; 4 | import android.os.StrictMode; 5 | 6 | import com.mvvm.utils.CrashHandler; 7 | 8 | /** 9 | * Created by chiclaim on 2016/02/24 10 | */ 11 | public class MvvmApplication extends Application { 12 | 13 | @Override 14 | public void onCreate() { 15 | if (BuildConfig.DEBUG) { 16 | StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 17 | .detectDiskReads() 18 | .detectDiskWrites() 19 | .detectNetwork() // or .detectAll() for all detectable problems 20 | .penaltyLog() 21 | .build()); 22 | StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 23 | .detectLeakedSqlLiteObjects() 24 | .detectLeakedClosableObjects() 25 | .penaltyLog() 26 | .penaltyDeath() 27 | .build()); 28 | } 29 | 30 | super.onCreate(); 31 | CrashHandler.getInstance().init(this, "crash_log_mvvm"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/adapter/BaseAdapter.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.adapter; 2 | 3 | import android.content.Context; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | 8 | import androidx.recyclerview.widget.RecyclerView; 9 | 10 | import com.mvvm.R; 11 | 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | 16 | /** 17 | * Created by chiclaim on 2016/01/27 18 | */ 19 | public abstract class BaseAdapter extends RecyclerView.Adapter { 20 | 21 | 22 | //内部维护数据源 23 | protected List list = new ArrayList<>(); 24 | 25 | public boolean mShowFooter; 26 | public boolean mShowHead; 27 | public final static int FOOTER_TYPE = 99; 28 | protected Context mContext; 29 | 30 | protected LayoutInflater inflater; 31 | 32 | public BaseAdapter(Context context) { 33 | mContext = context; 34 | inflater = LayoutInflater.from(context); 35 | } 36 | 37 | 38 | public static class UnknownViewHolder extends RecyclerView.ViewHolder { 39 | public UnknownViewHolder(View itemView) { 40 | super(itemView); 41 | } 42 | } 43 | 44 | public static class Footer extends RecyclerView.ViewHolder { 45 | public Footer(View itemView) { 46 | super(itemView); 47 | } 48 | } 49 | 50 | 51 | public T getModel(int position) { 52 | if (list.size() == 0) { 53 | return null; 54 | } 55 | return list.get(position); 56 | } 57 | 58 | public int getModelSize() { 59 | return list.size(); 60 | } 61 | 62 | 63 | public void showFooter() { 64 | hideHead(); 65 | mShowFooter = true; 66 | notifyDataSetChanged(); 67 | } 68 | 69 | public void hideFooter() { 70 | mShowFooter = false; 71 | notifyDataSetChanged(); 72 | } 73 | 74 | public void showHead() { 75 | mShowHead = true; 76 | hideFooter(); 77 | } 78 | 79 | public void hideHead() { 80 | mShowHead = false; 81 | } 82 | 83 | @Override 84 | public int getItemViewType(int position) { 85 | if (mShowFooter && position == getMyItemCount()) { 86 | return FOOTER_TYPE; 87 | } 88 | return getMyItemViewType(position); 89 | } 90 | 91 | @Override 92 | public void onBindViewHolder(RecyclerView.ViewHolder arg0, int positon) { 93 | int type = getItemViewType(positon); 94 | switch (type) { 95 | case FOOTER_TYPE: 96 | break; 97 | default: 98 | onMyBindViewHolder(arg0, mShowHead ? positon - 1 : positon); 99 | break; 100 | } 101 | } 102 | 103 | @Override 104 | public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { 105 | switch (viewType) { 106 | case FOOTER_TYPE: 107 | return new Footer(getLayout(R.layout.footer_loading_layout, viewGroup)); 108 | default: 109 | return onMyCreateViewHolder(viewGroup, viewType); 110 | } 111 | } 112 | 113 | @Override 114 | public int getItemCount() { 115 | return getMyItemCount() + (mShowFooter ? 1 : 0) + (mShowHead ? 1 : 0); 116 | } 117 | 118 | /** 119 | * 替代getItemViewType 120 | * 121 | * @return 122 | */ 123 | public int getMyItemCount() { 124 | return list.size(); 125 | } 126 | 127 | /** 128 | * 替代onCreateViewHolder 129 | * 130 | * @param parent 131 | * @param viewType 132 | * @return 133 | */ 134 | public abstract RecyclerView.ViewHolder onMyCreateViewHolder(ViewGroup parent, int viewType); 135 | 136 | /** 137 | * 替代onBindViewHolder 138 | * 139 | * @param viewHolder 140 | * @param position 141 | */ 142 | public abstract void onMyBindViewHolder(RecyclerView.ViewHolder viewHolder, int position); 143 | 144 | /** 145 | * 替代getItemViewType 146 | * 147 | * @param position 148 | * @return 149 | */ 150 | public abstract int getMyItemViewType(int position); 151 | 152 | 153 | public void appendItems(List items) { 154 | if (items == null || items.isEmpty()) { 155 | return; 156 | } 157 | //int startPosition = list.size(); 158 | list.addAll(items); 159 | //notifyItemRangeInserted(startPosition, items.size()); 160 | notifyDataSetChanged(); 161 | } 162 | 163 | public void appendItem(T item) { 164 | if (item == null) { 165 | return; 166 | } 167 | appendItems(Arrays.asList(item)); 168 | } 169 | 170 | 171 | public void removeAll() { 172 | list.clear(); 173 | hideFooter(); 174 | notifyDataSetChanged(); 175 | } 176 | 177 | public View getLayout(int layoutId, ViewGroup parent) { 178 | return inflater.inflate(layoutId, parent, false); 179 | } 180 | 181 | 182 | public RecyclerView.ViewHolder getUnKnowViewHolder(ViewGroup parent) { 183 | return new UnknownViewHolder(getLayout(R.layout.item_unknown, parent)); 184 | } 185 | 186 | } 187 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/adapter/ContributorAdapter.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.adapter; 2 | 3 | import android.content.Context; 4 | import androidx.databinding.DataBindingUtil; 5 | import androidx.recyclerview.widget.RecyclerView; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | 9 | import com.mvvm.R; 10 | import com.mvvm.databinding.ItemContributorBinding; 11 | import com.mvvm.model.Contributor; 12 | import com.squareup.picasso.Picasso; 13 | 14 | 15 | /** 16 | * Created by chiclaim on 2016/01/27 17 | */ 18 | public class ContributorAdapter extends BaseAdapter { 19 | 20 | public ContributorAdapter(Context context) { 21 | super(context); 22 | } 23 | 24 | @Override 25 | public RecyclerView.ViewHolder onMyCreateViewHolder(ViewGroup parent, int viewType) { 26 | ItemContributorBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_contributor, parent, false); 27 | ContributorViewHolder viewHolder = new ContributorViewHolder(binding.getRoot()); 28 | viewHolder.setBinding(binding); 29 | return viewHolder; 30 | } 31 | 32 | @Override 33 | public void onMyBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { 34 | ContributorViewHolder contributorViewHolder = (ContributorViewHolder) viewHolder; 35 | Contributor contributor = getModel(position); 36 | contributorViewHolder.getBinding().setVariable(com.mvvm.BR.contributor, contributor); 37 | contributorViewHolder.getBinding().executePendingBindings(); 38 | Picasso.with(mContext).load(contributor.getAvatar_url()). 39 | into(contributorViewHolder.binding.ivAvatar); 40 | } 41 | 42 | @Override 43 | public int getMyItemViewType(int position) { 44 | return 0; 45 | } 46 | 47 | 48 | public class ContributorViewHolder extends RecyclerView.ViewHolder { 49 | 50 | ItemContributorBinding binding; 51 | 52 | public void setBinding(ItemContributorBinding binding) { 53 | this.binding = binding; 54 | } 55 | 56 | public ItemContributorBinding getBinding() { 57 | return binding; 58 | } 59 | 60 | public ContributorViewHolder(View itemView) { 61 | super(itemView); 62 | } 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/adapter/SearchAdapter.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.adapter; 2 | 3 | import android.content.Context; 4 | import androidx.databinding.DataBindingUtil; 5 | import androidx.recyclerview.widget.RecyclerView; 6 | import android.view.ViewGroup; 7 | 8 | import com.mvvm.BR; 9 | import com.mvvm.R; 10 | import com.mvvm.databinding.ItemSearchBinding; 11 | 12 | /** 13 | * Created by chiclaim on 2016/02/26 14 | */ 15 | public class SearchAdapter extends BaseAdapter { 16 | 17 | 18 | public SearchAdapter(Context context) { 19 | super(context); 20 | } 21 | 22 | @Override 23 | public RecyclerView.ViewHolder onMyCreateViewHolder(ViewGroup parent, int viewType) { 24 | ItemSearchBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_search, parent, false); 25 | return new ItemViewHolder(binding); 26 | } 27 | 28 | @Override 29 | public void onMyBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { 30 | ItemViewHolder itemViewHolder = (ItemViewHolder) viewHolder; 31 | String value = getModel(position); 32 | itemViewHolder.getBinding().setVariable(BR.value, value); 33 | itemViewHolder.getBinding().executePendingBindings(); 34 | } 35 | 36 | @Override 37 | public int getMyItemViewType(int position) { 38 | return 0; 39 | } 40 | 41 | 42 | class ItemViewHolder extends RecyclerView.ViewHolder { 43 | 44 | ItemSearchBinding itemBinding; 45 | 46 | public ItemViewHolder(ItemSearchBinding itemBinding) { 47 | super(itemBinding.getRoot()); 48 | this.itemBinding = itemBinding; 49 | } 50 | 51 | public ItemSearchBinding getBinding() { 52 | return itemBinding; 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/event/UserFollowEvent.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.event; 2 | 3 | import android.view.View; 4 | 5 | /** 6 | * Created by chiclaim on 2016/02/21 7 | */ 8 | public interface UserFollowEvent { 9 | void follow(View view); 10 | void unFollow(View view); 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/exception/AccessDenyException.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.exception; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/25 5 | */ 6 | public class AccessDenyException extends RuntimeException { 7 | public AccessDenyException(String detailMessage) { 8 | super(detailMessage); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/exception/ConversionException.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.exception; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/26 5 | */ 6 | public class ConversionException extends RuntimeException { 7 | public ConversionException(String detailMessage) { 8 | super(detailMessage); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/exception/NetworkException.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.exception; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/25 5 | */ 6 | public class NetworkException extends RuntimeException { 7 | public NetworkException(String detailMessage) { 8 | super(detailMessage); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/exception/Non200HttpException.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.exception; 2 | 3 | /** 4 | * A non-200 HTTP status code was received from the server

5 | * Created by chiclaim on 2016/02/26 6 | */ 7 | public class Non200HttpException extends RuntimeException { 8 | public Non200HttpException(String detailMessage) { 9 | super(detailMessage); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/exception/UnKnowException.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.exception; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/26 5 | */ 6 | public class UnKnowException extends RuntimeException { 7 | public UnKnowException(String detailMessage) { 8 | super(detailMessage); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/ApiServiceFactory.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.http; 2 | 3 | import android.util.Log; 4 | 5 | import com.mvvm.exception.AccessDenyException; 6 | import com.mvvm.exception.ConversionException; 7 | import com.mvvm.exception.UnKnowException; 8 | 9 | import retrofit.ErrorHandler; 10 | import retrofit.RequestInterceptor; 11 | import retrofit.RestAdapter; 12 | import retrofit.RetrofitError; 13 | 14 | /** 15 | * Created by chiclaim on 2016/01/26 16 | */ 17 | public class ApiServiceFactory { 18 | 19 | //server source code please see: 20 | // https://github.com/chiclaim/android_mvvm_server 21 | private static final String BASE_URL = "http://192.168.1.109:8080/AndroidMvvmServer"; 22 | 23 | private static RequestInterceptor requestInterceptor = new RequestInterceptor() { 24 | @Override 25 | public void intercept(RequestFacade request) { 26 | request.addHeader("Authorization", "test"); 27 | } 28 | }; 29 | 30 | private static class NetWorkErrorHandler implements ErrorHandler { 31 | @Override 32 | public Throwable handleError(RetrofitError error) { 33 | retrofit.client.Response r = error.getResponse(); 34 | if (r != null && r.getStatus() == 401) { 35 | Log.e("ErrorHandler", "---------> access deny code=401"); 36 | return new AccessDenyException(error.getMessage()); 37 | } else if (error.getKind() == RetrofitError.Kind.NETWORK) { 38 | Log.e("ErrorHandler", "---------> An IOException occurred while communicating to the server"); 39 | //return new NetworkException(cause.getMessage()); 40 | } else if (error.getKind() == RetrofitError.Kind.HTTP) { 41 | Log.e("ErrorHandler", "---------> A non-200 HTTP status code was received from the server"); 42 | //return new Non200HttpException(cause.getMessage()); 43 | } else if (error.getKind() == RetrofitError.Kind.CONVERSION) { 44 | Log.e("ErrorHandler", "---------> An exception was thrown while (de)serializing a body"); 45 | return new ConversionException(error.getMessage()); 46 | } else if (error.getKind() == RetrofitError.Kind.UNEXPECTED) { 47 | Log.e("ErrorHandler", "---------> An internal error occurred while attempting to execute a request. " + 48 | "It is best practice to re-throw this exception so your application crashes."); 49 | return new UnKnowException(error.getMessage()); 50 | } 51 | return error.getCause(); 52 | } 53 | } 54 | 55 | private static RestAdapter restAdapter = new RestAdapter 56 | .Builder() 57 | .setLogLevel(RestAdapter.LogLevel.FULL) 58 | .setEndpoint(BASE_URL) 59 | .setErrorHandler(new NetWorkErrorHandler()) 60 | .setRequestInterceptor(requestInterceptor) 61 | .build(); 62 | 63 | 64 | public static S createService(Class serviceClazz) { 65 | return restAdapter.create(serviceClazz); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/ApiServiceFactory2.java: -------------------------------------------------------------------------------- 1 | //package com.mvvm.http; 2 | // 3 | //import android.text.TextUtils; 4 | // 5 | //import java.io.IOException; 6 | // 7 | //import okhttp3.Interceptor; 8 | //import okhttp3.OkHttpClient; 9 | //import okhttp3.Request; 10 | //import okhttp3.Response; 11 | //import okhttp3.logging.HttpLoggingInterceptor; 12 | //import retrofit2.Retrofit; 13 | //import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; 14 | //import retrofit2.converter.gson.GsonConverterFactory; 15 | // 16 | ///** 17 | // * Created by chiclaim on 2016/01/26 18 | // */ 19 | //public class ApiServiceFactory2 { 20 | // 21 | // //private static final String BASE_URL = "https://api.github.com/"; 22 | // private static final String BASE_URL = "http://192.168.1.109:8080/JavaWebHttp2/"; 23 | // 24 | // static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 25 | // static HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 26 | // 27 | // 28 | // private static Retrofit.Builder builder = new Retrofit.Builder() 29 | // .baseUrl(BASE_URL) 30 | // //.addCallAdapterFactory(ErrorCallAdapterFactory.create()) 31 | // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 32 | // .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) 33 | // .addConverterFactory(GsonConverterFactory.create()); 34 | // 35 | // public static S createService(Class serviceClazz) { 36 | // return createService(serviceClazz, null); 37 | // } 38 | // 39 | // static { 40 | // // set your desired log level 41 | // logging.setLevel(HttpLoggingInterceptor.Level.BODY); 42 | // httpClient.interceptors().add(logging); 43 | // 44 | // //httpClient.addNetworkInterceptor 45 | // 46 | // } 47 | // 48 | // 49 | // public static S createService(Class serviceClazz, final String authorization) { 50 | // 51 | // //Gson gson = new GsonBuilder() 52 | // // .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'") 53 | // // .create(); 54 | // 55 | // //httpClient.interceptors().clear(); 56 | // 57 | // if (!TextUtils.isEmpty(authorization)) { 58 | // httpClient.interceptors().add(new Interceptor() { 59 | // @Override 60 | // public Response intercept(Chain chain) throws IOException { 61 | // Request original = chain.request(); 62 | // //addHead() 63 | // Request.Builder requestBuilder = original.newBuilder() 64 | // .header("Authorization", authorization) 65 | // .header("Accept", "applicaton/json") 66 | // .method(original.method(), original.body()); 67 | // 68 | // Request request = requestBuilder.build(); 69 | // return chain.proceed(request); 70 | // } 71 | // }); 72 | // } 73 | // 74 | // 75 | // OkHttpClient hClient = httpClient.build(); 76 | // Retrofit retrofit = builder.client(hClient).build(); 77 | // return retrofit.create(serviceClazz); 78 | // } 79 | // 80 | //} 81 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/ErrorCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | //package com.mvvm.http; 2 | // 3 | //import com.mvvm.exception.AccessDenyException; 4 | // 5 | //import java.io.IOException; 6 | //import java.lang.annotation.Annotation; 7 | //import java.lang.reflect.Type; 8 | // 9 | //import retrofit2.Call; 10 | //import retrofit2.CallAdapter; 11 | //import retrofit2.Response; 12 | //import retrofit2.Retrofit; 13 | // 14 | //public class ErrorCallAdapterFactory extends CallAdapter.Factory { 15 | // public static CallAdapter.Factory create() { 16 | // return new ErrorCallAdapterFactory(); 17 | // } 18 | // 19 | // @Override 20 | // public CallAdapter get(final Type returnType, Annotation[] annotations, Retrofit retrofit) { 21 | // // if returnType is retrofit2.Call, do nothing 22 | // //if (getRawType(returnType) == Call.class) { 23 | // // return null; 24 | // //} 25 | // 26 | // return new CallAdapter() { 27 | // @Override 28 | // public Type responseType() { 29 | // return returnType; 30 | // } 31 | // 32 | // @Override 33 | // public Object adapt(Call call) { 34 | // try { 35 | // Response res = call.execute(); 36 | // getCallResponseType(res.code()); 37 | // return res.body(); 38 | // } catch (IOException e) { 39 | // throw new RuntimeException(); // do something better 40 | // } 41 | // } 42 | // }; 43 | // } 44 | // 45 | // static void getCallResponseType(int code) { 46 | // if (code == 401) { 47 | // throw new AccessDenyException(); 48 | // } 49 | // } 50 | //} -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/GitHubApi.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.http; 2 | 3 | import com.mvvm.model.AuthToken; 4 | import com.mvvm.model.Contributor; 5 | 6 | import java.util.List; 7 | 8 | import retrofit.http.GET; 9 | import rx.Observable; 10 | 11 | public interface GitHubApi { 12 | 13 | // @GET("repos/{owner}/{repo}/contributors") 14 | // Call> contributors(@Path("owner") String owner, 15 | // @Path("repo") String repo); 16 | // 17 | // @GET() 18 | // Call> nextContributors(@Url String nextUrl); 19 | 20 | 21 | @GET("/contributor/list") 22 | Observable> contributors(); 23 | 24 | @GET("/token") 25 | AuthToken refreshToken(); 26 | 27 | 28 | } -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/NetErrorType.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.http; 2 | 3 | import com.mvvm.exception.ConversionException; 4 | 5 | /** 6 | * Created by chiclaim on 2016/02/26 7 | */ 8 | public class NetErrorType { 9 | 10 | public static final int TYPE_ERROR_TIME_OUT = 1; 11 | public static final int TYPE_ERROR_UNKNOW_HOST = 2; 12 | public static final int TYPE_ERROR_CONNECT = 3; 13 | public static final int TYPE_ERROR_CONVERSION = 6; 14 | public static final int TYPE_ERROR_UNKNOW = 20; 15 | 16 | public static class ErrorType { 17 | public int type; 18 | public String msg; 19 | 20 | public ErrorType(int type, String msg) { 21 | this.type = type; 22 | this.msg = msg; 23 | } 24 | } 25 | 26 | public static ErrorType getErrorType(Throwable t) { 27 | if (t instanceof java.net.SocketTimeoutException) { 28 | return new ErrorType(TYPE_ERROR_TIME_OUT, "连接超时"); 29 | } else if (t instanceof java.net.UnknownHostException) { 30 | return new ErrorType(TYPE_ERROR_UNKNOW_HOST, "网络不可用"); 31 | } else if (t instanceof java.net.ConnectException) { 32 | return new ErrorType(TYPE_ERROR_CONNECT, "网络不可用"); 33 | } else if (t instanceof ConversionException) { 34 | return new ErrorType(TYPE_ERROR_CONVERSION, "JSON解析失败"); 35 | } 36 | return new ErrorType(TYPE_ERROR_UNKNOW, "未知错误"); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/SearchApi.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.http; 2 | 3 | import java.util.List; 4 | 5 | import retrofit.http.GET; 6 | import retrofit.http.Query; 7 | import rx.Observable; 8 | 9 | /** 10 | * Created by chiclaim on 2016/02/26 11 | */ 12 | public interface SearchApi { 13 | 14 | @GET("/search") 15 | Observable> search(@Query("key") String key); 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/http/SynchronousCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | //package com.mvvm.http; 2 | // 3 | //import java.io.IOException; 4 | //import java.lang.annotation.Annotation; 5 | //import java.lang.reflect.Type; 6 | // 7 | //import retrofit2.Call; 8 | //import retrofit2.CallAdapter; 9 | //import retrofit2.Retrofit; 10 | // 11 | //public class SynchronousCallAdapterFactory extends CallAdapter.Factory { 12 | // public static CallAdapter.Factory create() { 13 | // return new SynchronousCallAdapterFactory(); 14 | // } 15 | // 16 | // @Override 17 | // public CallAdapter get(final Type returnType, Annotation[] annotations, Retrofit retrofit) { 18 | // // if returnType is retrofit2.Call, do nothing 19 | // if (getRawType(returnType) == Call.class) { 20 | // return null; 21 | // } 22 | // 23 | // return new CallAdapter() { 24 | // @Override 25 | // public Type responseType() { 26 | // return returnType; 27 | // } 28 | // 29 | // @Override 30 | // public Object adapt(Call call) { 31 | // try { 32 | // return call.execute().body(); 33 | // } catch (IOException e) { 34 | // throw new RuntimeException(); // do something better 35 | // } 36 | // } 37 | // }; 38 | // } 39 | //} -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/model/AuthToken.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.model; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/24 5 | */ 6 | public class AuthToken { 7 | 8 | private String token; 9 | 10 | public String getToken() { 11 | return token; 12 | } 13 | 14 | public void setToken(String token) { 15 | this.token = token; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/model/Book.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.model; 2 | 3 | /** 4 | * Created by chiclaim on 2016/02/20 5 | */ 6 | public class Book { 7 | 8 | private int id; 9 | 10 | public int getId() { 11 | return id; 12 | } 13 | 14 | public void setId(int id) { 15 | this.id = id; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/model/Contributor.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.model; 2 | 3 | public class Contributor { 4 | private String login; 5 | private String avatar_url; 6 | private long contributions; 7 | 8 | public String getLogin() { 9 | return login; 10 | } 11 | 12 | public void setLogin(String login) { 13 | this.login = login; 14 | } 15 | 16 | public String getAvatar_url() { 17 | return avatar_url; 18 | } 19 | 20 | public void setAvatar_url(String avatar_url) { 21 | this.avatar_url = avatar_url; 22 | } 23 | 24 | public long getContributions() { 25 | return contributions; 26 | } 27 | 28 | public void setContributions(long contributions) { 29 | this.contributions = contributions; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "login='" + login + '\'' + 35 | ", contributions=" + contributions + 36 | '\n'; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/model/User.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.model; 2 | 3 | import androidx.databinding.BaseObservable; 4 | import androidx.databinding.Bindable; 5 | import android.util.Log; 6 | 7 | import com.mvvm.BR; 8 | 9 | /** 10 | * Created by chiclaim on 2016/02/18 11 | */ 12 | public class User extends BaseObservable{ 13 | 14 | private String userName; 15 | private String realName; 16 | private String mobile; 17 | private int age; 18 | 19 | /** 20 | * 注意: 在BR里对应的常量为follow 21 | */ 22 | private boolean isFollow; 23 | 24 | 25 | public User(String realName, String mobile) { 26 | this.realName = realName; 27 | this.mobile = mobile; 28 | Log.d("User", "user construct invoked"); 29 | } 30 | 31 | public User() { 32 | } 33 | 34 | @Bindable 35 | public boolean isFollow() { 36 | return isFollow; 37 | } 38 | 39 | public void setIsFollow(boolean isFollow) { 40 | this.isFollow = isFollow; 41 | notifyPropertyChanged(BR.follow); 42 | } 43 | 44 | @Bindable 45 | public String getUserName() { 46 | return userName; 47 | } 48 | 49 | public void setUserName(String userName) { 50 | this.userName = userName; 51 | notifyPropertyChanged(BR.userName); 52 | } 53 | 54 | @Bindable 55 | public int getAge() { 56 | return age; 57 | } 58 | 59 | 60 | public void setAge(int age) { 61 | this.age = age; 62 | notifyPropertyChanged(BR.age); 63 | } 64 | 65 | @Bindable 66 | public String getRealName() { 67 | return realName; 68 | } 69 | 70 | public void setRealName(String realName) { 71 | this.realName = realName; 72 | notifyPropertyChanged(BR.realName); 73 | } 74 | 75 | @Bindable 76 | public String getMobile() { 77 | return mobile; 78 | } 79 | 80 | public void setMobile(String mobile) { 81 | this.mobile = mobile; 82 | notifyPropertyChanged(BR.mobile); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/model/UserField.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.model; 2 | 3 | import androidx.databinding.ObservableField; 4 | 5 | /** 6 | * Created by chiclaim on 2016/02/18 7 | */ 8 | public class UserField { 9 | 10 | public final ObservableField realName = new ObservableField<>(); 11 | public final ObservableField mobile = new ObservableField<>(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import androidx.appcompat.app.ActionBar; 6 | import androidx.appcompat.app.AppCompatActivity; 7 | import android.view.MenuItem; 8 | 9 | /** 10 | * Created by chiclaim on 2016/02/18 11 | */ 12 | public class BaseActivity extends AppCompatActivity { 13 | 14 | 15 | private LoadingDialog loadingDialog; 16 | 17 | @Override 18 | public void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | 21 | ActionBar actionBar = getSupportActionBar(); 22 | if (actionBar != null) { 23 | actionBar.setDisplayHomeAsUpEnabled(true); 24 | actionBar.setDisplayShowHomeEnabled(false); 25 | actionBar.setDisplayShowTitleEnabled(true); 26 | actionBar.setDisplayUseLogoEnabled(false); 27 | } 28 | 29 | loadingDialog = new LoadingDialog(this); 30 | } 31 | 32 | /** 33 | * 显示加载对话框 34 | */ 35 | public void showLoadingDialog() { 36 | if (loadingDialog != null && !loadingDialog.isShowing()) { 37 | loadingDialog.show(); 38 | } 39 | } 40 | 41 | /** 42 | * 隐藏加载对话框 43 | */ 44 | public void hideLoadingDialog() { 45 | if (loadingDialog != null && loadingDialog.isShowing()) { 46 | loadingDialog.dismiss(); 47 | } 48 | } 49 | 50 | public void launchActivity(Class clazz) { 51 | Intent intent = new Intent(this, clazz); 52 | startActivity(intent); 53 | } 54 | 55 | 56 | @Override 57 | public boolean onOptionsItemSelected(MenuItem item) { 58 | switch (item.getItemId()) { 59 | case android.R.id.home: 60 | finish(); 61 | break; 62 | } 63 | return super.onOptionsItemSelected(item); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/ConverterActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import androidx.databinding.BindingConversion; 4 | import androidx.databinding.DataBindingUtil; 5 | import android.graphics.drawable.ColorDrawable; 6 | import android.os.Bundle; 7 | import android.util.Log; 8 | import android.view.View; 9 | 10 | import com.mvvm.R; 11 | import com.mvvm.databinding.ConverterBinding; 12 | import com.mvvm.event.UserFollowEvent; 13 | import com.mvvm.model.User; 14 | 15 | /** 16 | * Created by chiclaim on 2016/02/23 17 | */ 18 | public class ConverterActivity extends BaseActivity implements UserFollowEvent { 19 | 20 | private User user; 21 | 22 | @Override 23 | public void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | ConverterBinding binding = DataBindingUtil.setContentView(this, 26 | R.layout.activity_converter); 27 | user = new User(); 28 | binding.setUser(user); 29 | binding.setUserFollowEvent(this); 30 | 31 | } 32 | 33 | @Override 34 | public void follow(View view) { 35 | user.setIsFollow(true); 36 | } 37 | 38 | @Override 39 | public void unFollow(View view) { 40 | user.setIsFollow(false); 41 | } 42 | 43 | 44 | //Note:最新版本的 dataBinding插件 在设置background 会自动把color转成ColorDrawable 45 | //所以不需要以下转换方法,如果创建了该方法,系统则会调用. 46 | @BindingConversion 47 | public static ColorDrawable convertColorToDrawable(int color) { 48 | Log.d("BindingConversion", "convertColorToDrawable:" + color); 49 | return new ColorDrawable(color); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/CustomSetterActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import androidx.databinding.BindingAdapter; 4 | import androidx.databinding.DataBindingUtil; 5 | import android.graphics.drawable.Drawable; 6 | import android.os.Bundle; 7 | import android.text.SpannableString; 8 | import android.text.Spanned; 9 | import android.text.style.TextAppearanceSpan; 10 | import android.util.Log; 11 | import android.view.View; 12 | import android.widget.ImageView; 13 | import android.widget.TextView; 14 | 15 | import com.mvvm.R; 16 | import com.mvvm.databinding.CustomSetterBinding; 17 | import com.mvvm.model.User; 18 | import com.squareup.picasso.Picasso; 19 | 20 | /** 21 | * 22 | * 23 | * Created by chiclaim on 2016/02/23 24 | */ 25 | public class CustomSetterActivity extends BaseActivity { 26 | 27 | //private User user; 28 | private CustomSetterBinding binding; 29 | private String errorAvatar = "http error"; 30 | private String avatar1 = "https://avatars.githubusercontent.com/u/133019?v=3"; 31 | private String avatar2 = "https://avatars.githubusercontent.com/u/18877?v=3"; 32 | 33 | @Override 34 | public void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | binding = DataBindingUtil.setContentView(this, R.layout.activity_custom_setter); 37 | User user = new User(); 38 | binding.setLeftPadding(20); 39 | binding.setAvatar(avatar1); 40 | binding.setErrorAvatar("error url"); 41 | } 42 | 43 | @BindingAdapter("android:paddingLeft") 44 | public static void setPaddingLeft(View view, int padding) { 45 | Log.d("BindingAdapter", "setPaddingLeft(View view, int padding)"); 46 | view.setPadding(padding, 47 | view.getPaddingTop(), 48 | view.getPaddingRight(), 49 | view.getPaddingBottom()); 50 | } 51 | 52 | // @dimen/padding value is a float 53 | @BindingAdapter("android:paddingLeft") 54 | public static void setPaddingLeft(View view, float padding) { 55 | Log.d("BindingAdapter", "setPaddingLeft(View view, float padding)"); 56 | view.setPadding((int) padding, 57 | view.getPaddingTop(), 58 | view.getPaddingRight(), 59 | view.getPaddingBottom()); 60 | } 61 | 62 | @BindingAdapter("android:paddingLeft") 63 | public static void setPaddingLeft(View view, int oldPadding, int newPadding) { 64 | Log.d("BindingAdapter", "setPaddingLeft(View view, int oldPadding, int newPadding)"); 65 | if (oldPadding != newPadding) { 66 | view.setPadding(newPadding, 67 | view.getPaddingTop(), 68 | view.getPaddingRight(), 69 | view.getPaddingBottom()); 70 | } 71 | } 72 | 73 | @BindingAdapter({"imageUrl"}) 74 | public static void loadImage(ImageView view, String url) { 75 | Log.d("BindingAdapter", "loadImage(ImageView view, String url)"); 76 | Log.d("BindingAdapter", url + ""); 77 | Picasso.with(view.getContext()).load(url).into(view); 78 | } 79 | 80 | /** 81 | * 在自定义setter方法,通过binding设置属性的时候,都会有oldValue和newValue, 82 | * 如果需要用到oldValue的时候,可以使用类似签名的函数 83 | * 84 | * @param view 85 | * @param url 86 | * @param newUrl 87 | */ 88 | @BindingAdapter({"imageUrl"}) 89 | public static void loadImage(ImageView view, String url, String newUrl) { 90 | Log.d("BindingAdapter", "loadImage(ImageView view, String url,String newUrl)"); 91 | Log.d("BindingAdapter", "oldUrl" + url); 92 | Log.d("BindingAdapter", "newUrl" + newUrl); 93 | Picasso.with(view.getContext()).load(newUrl).into(view); 94 | } 95 | 96 | @BindingAdapter({"imageUrl", "error"}) 97 | public static void loadImage(ImageView view, String url, Drawable error) { 98 | Log.d("BindingAdapter", "loadImage(ImageView view, String url,Drawable error)"); 99 | Picasso.with(view.getContext()).load(url).error(error).into(view); 100 | } 101 | 102 | @BindingAdapter("spanText") 103 | public static void setText(TextView textView, String value) { 104 | Log.d("BindingAdapter", "setText(TextView textView,String value)"); 105 | SpannableString styledText = new SpannableString(value); 106 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style0), 107 | 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 108 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style1), 109 | 5, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 110 | styledText.setSpan(new TextAppearanceSpan(textView.getContext(), R.style.style0), 111 | 12, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 112 | textView.setText(styledText, TextView.BufferType.SPANNABLE); 113 | } 114 | 115 | public void setLeftPadding(View view) { 116 | binding.setLeftPadding(binding.getLeftPadding() == 20 ? 40 : 20); 117 | } 118 | 119 | 120 | public void loadOtherImage(View view) { 121 | //test old value and new value 122 | if (binding.getAvatar().equals(avatar1)) { 123 | binding.setAvatar(avatar2); 124 | } else { 125 | binding.setAvatar(avatar1); 126 | } 127 | } 128 | 129 | public void loadRightImage(View view) { 130 | if (errorAvatar.equals(binding.getErrorAvatar())) { 131 | binding.setErrorAvatar(avatar1); 132 | } else { 133 | binding.setErrorAvatar(errorAvatar); 134 | } 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/DataBindSimpleActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import androidx.databinding.DataBindingUtil; 4 | import android.os.AsyncTask; 5 | import android.os.Bundle; 6 | 7 | import com.mvvm.R; 8 | import com.mvvm.databinding.ActivitySimpleBinding; 9 | import com.mvvm.model.User; 10 | 11 | public class DataBindSimpleActivity extends BaseActivity { 12 | 13 | private ActivitySimpleBinding binding; 14 | 15 | 16 | @Override 17 | public void onCreate(Bundle savedInstanceState) { 18 | super.onCreate(savedInstanceState); 19 | binding = DataBindingUtil.setContentView(this, R.layout.activity_simple); 20 | fetchData(); 21 | 22 | } 23 | 24 | /** 25 | * 模拟获取数据 26 | */ 27 | private void fetchData() { 28 | new AsyncTask() { 29 | 30 | @Override 31 | protected void onPreExecute() { 32 | super.onPreExecute(); 33 | showLoadingDialog(); 34 | } 35 | 36 | @Override 37 | protected Void doInBackground(Void... params) { 38 | try { 39 | Thread.sleep(2000); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | return null; 44 | } 45 | 46 | @Override 47 | protected void onPostExecute(Void aVoid) { 48 | super.onPostExecute(aVoid); 49 | hideLoadingDialog(); 50 | User user = new User("Chiclaim", "13512341234"); 51 | binding.setUser(user); 52 | //binding.setVariable(com.mvvm.BR.user, user); 53 | } 54 | }.execute(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/ELActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import androidx.databinding.DataBindingUtil; 6 | import android.os.Bundle; 7 | import android.util.SparseArray; 8 | import android.view.View; 9 | 10 | import com.mvvm.R; 11 | import com.mvvm.databinding.ActivityElBinding; 12 | import com.mvvm.event.UserFollowEvent; 13 | import com.mvvm.model.User; 14 | 15 | /** 16 | * Created by chiclaim on 2016/02/19 17 | */ 18 | public class ELActivity extends BaseActivity implements UserFollowEvent{ 19 | 20 | //Null Coalescing Operator 21 | //Collections 22 | //String Literals 23 | //Resources 24 | 25 | ActivityElBinding binding; 26 | 27 | public User user; 28 | 29 | public int index; 30 | 31 | public SparseArray sparseArray = new SparseArray<>(); 32 | 33 | 34 | public static void launch(Context context) { 35 | Intent intent = new Intent(context, ELActivity.class); 36 | context.startActivity(intent); 37 | } 38 | 39 | @Override 40 | public void onCreate(Bundle savedInstanceState) { 41 | super.onCreate(savedInstanceState); 42 | binding = DataBindingUtil.setContentView(this, R.layout.activity_el); 43 | user = new User(); 44 | user.setUserName("Johnny"); 45 | user.setRealName(null); 46 | binding.setUser(user); 47 | 48 | sparseArray.put(0, "one"); 49 | sparseArray.put(1, "two"); 50 | sparseArray.put(2, "three"); 51 | 52 | binding.setIndex(index); 53 | binding.setSparse(sparseArray); 54 | 55 | binding.setEvent(this); 56 | } 57 | 58 | 59 | public void collectionSample(View view) { 60 | if (index >= sparseArray.size() - 1) { 61 | index = 0; 62 | } else { 63 | index++; 64 | } 65 | binding.setIndex(index); 66 | binding.setSparse(sparseArray); 67 | } 68 | 69 | public void coalescingSample(View view) { 70 | if (user.getRealName() != null) { 71 | user.setRealName(null); 72 | user.setUserName("Johnny"); 73 | } else { 74 | user.setRealName("张三"); 75 | user.setUserName(null); 76 | } 77 | } 78 | 79 | @Override 80 | public void follow(View view) { 81 | user.setIsFollow(true); 82 | } 83 | 84 | @Override 85 | public void unFollow(View view) { 86 | user.setIsFollow(false); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/GitHubContributorsActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | 7 | import androidx.recyclerview.widget.RecyclerView; 8 | import android.widget.TextView; 9 | 10 | import com.mvvm.R; 11 | import com.mvvm.adapter.BaseAdapter; 12 | import com.mvvm.adapter.ContributorAdapter; 13 | import com.mvvm.exception.AccessDenyException; 14 | import com.mvvm.http.ApiServiceFactory; 15 | import com.mvvm.http.GitHubApi; 16 | import com.mvvm.http.NetErrorType; 17 | import com.mvvm.model.AuthToken; 18 | import com.mvvm.model.Contributor; 19 | import com.mvvm.utils.DividerItemDecoration; 20 | import com.mvvm.utils.RecyclerViewUtils; 21 | 22 | import java.util.List; 23 | 24 | import rx.Observable; 25 | import rx.Observer; 26 | import rx.Subscriber; 27 | import rx.android.schedulers.AndroidSchedulers; 28 | import rx.functions.Func1; 29 | import rx.schedulers.Schedulers; 30 | 31 | 32 | /** 33 | * RxJava+Retrofit1.9, Authorization by token

34 | * Created by chiclaim on 2016/02/18 35 | */ 36 | 37 | public class GitHubContributorsActivity extends BaseActivity { 38 | 39 | private GitHubApi gitHubApi = ApiServiceFactory.createService(GitHubApi.class); 40 | 41 | public RecyclerView rvContent; 42 | public TextView tvTip; 43 | public BaseAdapter adapter; 44 | private boolean loading; 45 | 46 | 47 | private RecyclerView.OnScrollListener scrollListener; 48 | 49 | 50 | public static void launch(Context context) { 51 | Intent intent = new Intent(context, GitHubContributorsActivity.class); 52 | context.startActivity(intent); 53 | } 54 | 55 | @Override 56 | public void onCreate(Bundle savedInstanceState) { 57 | super.onCreate(savedInstanceState); 58 | setContentView(R.layout.activity_github_contributors); 59 | initViews(); 60 | 61 | showLoadingDialog(); 62 | requestContributes(); 63 | } 64 | 65 | private void initViews() { 66 | 67 | tvTip = (TextView) findViewById(R.id.tv_tips); 68 | rvContent = (RecyclerView) findViewById(R.id.recyclerView); 69 | adapter = new ContributorAdapter(this); 70 | RecyclerViewUtils.setLinearManagerAndAdapter(rvContent, adapter); 71 | rvContent.addItemDecoration(DividerItemDecoration.newVertical(this, 72 | R.dimen.list_divider_height, R.color.divider_color)); 73 | scrollListener = new RecyclerView.OnScrollListener() { 74 | @Override 75 | public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 76 | super.onScrolled(recyclerView, dx, dy); 77 | //check for scroll down 78 | if (adapter.getModelSize() == 0) { 79 | return; 80 | } 81 | if (dy > 0) { 82 | // LinearLayoutManager mLayoutManager = (LinearLayoutManager) 83 | // rvContent.getLayoutManager(); 84 | // int visibleItemCount = mLayoutManager.getChildCount(); 85 | // int totalItemCount = mLayoutManager.getItemCount(); 86 | // int pastVisibleItems = mLayoutManager.findFirstVisibleItemPosition(); 87 | // if (!isLast && !loading) { 88 | // if ((visibleItemCount + pastVisibleItems) >= totalItemCount) { 89 | // loading = true; 90 | // adapter.showFooter(); 91 | // requestContributes(); 92 | // } 93 | // } 94 | } 95 | } 96 | }; 97 | 98 | rvContent.addOnScrollListener(scrollListener); 99 | } 100 | 101 | public Observable refreshToken() { 102 | return Observable.create(new Observable.OnSubscribe() { 103 | @Override 104 | public void call(Subscriber observer) { 105 | try { 106 | if (!observer.isUnsubscribed()) { 107 | observer.onNext(gitHubApi.refreshToken()); 108 | observer.onCompleted(); 109 | } 110 | } catch (Exception e) { 111 | observer.onError(e); 112 | } 113 | } 114 | }).subscribeOn(Schedulers.io()); 115 | } 116 | 117 | private Func1> refreshTokenAndRetry(final Observable toBeResumed) { 118 | return new Func1>() { 119 | @Override 120 | public Observable call(Throwable throwable) { 121 | throwable.printStackTrace(); 122 | // Here check if the error thrown really is a 401 123 | if (isHttp401Error(throwable)) { 124 | return refreshToken().flatMap(new Func1>() { 125 | @Override 126 | public Observable call(AuthToken token) { 127 | return toBeResumed; 128 | } 129 | }); 130 | } 131 | // re-throw this error because it's not recoverable from here 132 | return Observable.error(throwable); 133 | } 134 | 135 | public boolean isHttp401Error(Throwable throwable) { 136 | return throwable instanceof AccessDenyException; 137 | } 138 | 139 | }; 140 | } 141 | 142 | private void requestContributes() { 143 | Observable> observable = gitHubApi.contributors(); 144 | observable.onErrorResumeNext(refreshTokenAndRetry(observable)) 145 | .subscribeOn(Schedulers.io()) 146 | .observeOn(AndroidSchedulers.mainThread()) 147 | .subscribe(new Observer>() { 148 | @Override 149 | public void onCompleted() { 150 | hideLoadingDialog(); 151 | } 152 | 153 | @Override 154 | public void onError(Throwable t) { 155 | hideLoadingDialog(); 156 | t.printStackTrace(); 157 | loading = false; 158 | tvTip.setText(t.getClass().getName() + "\n" + t.getMessage()); 159 | 160 | NetErrorType.ErrorType error = NetErrorType.getErrorType(t); 161 | tvTip.append("\n"); 162 | tvTip.append(error.msg); 163 | } 164 | 165 | public void onNext(List response) { 166 | adapter.appendItems(response); 167 | } 168 | }); 169 | 170 | } 171 | 172 | @Override 173 | public void onDestroy() { 174 | super.onDestroy(); 175 | rvContent.removeOnScrollListener(scrollListener); 176 | } 177 | } -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/LoadingDialog.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.app.ProgressDialog; 4 | import android.content.Context; 5 | import android.os.Bundle; 6 | import android.text.TextUtils; 7 | import android.widget.TextView; 8 | 9 | import com.mvvm.R; 10 | 11 | /** 12 | * created by chiclaim 13 | */ 14 | public class LoadingDialog extends ProgressDialog { 15 | private String tip; 16 | 17 | public LoadingDialog(Context context) { 18 | super(context, R.style.loading_dialog); 19 | } 20 | 21 | public LoadingDialog(Context context, int theme) { 22 | super(context, theme); 23 | } 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | setContentView(R.layout.dialog_common_loading); 29 | if (!TextUtils.isEmpty(tip)) { 30 | TextView tvTip = (TextView) findViewById(android.R.id.message); 31 | tvTip.setText(tip); 32 | } 33 | setCancelable(false); 34 | } 35 | 36 | @Override 37 | public void setMessage(CharSequence message) { 38 | tip = message.toString(); 39 | } 40 | } -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import androidx.appcompat.app.ActionBar; 6 | import android.util.Log; 7 | import android.view.View; 8 | 9 | import com.mvvm.BR; 10 | import com.mvvm.R; 11 | 12 | /** 13 | * 1, 用户修改用户名 , 如果多界面都使用了用户名,则需要在使用的界面同步更新. 14 | * 2, 界面列表使用dataBinding 15 | */ 16 | public class MainActivity extends BaseActivity { 17 | 18 | @Override 19 | public void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.activity_main); 22 | ActionBar actionBar = getSupportActionBar(); 23 | if (actionBar != null) { 24 | actionBar.setDisplayHomeAsUpEnabled(false); 25 | } 26 | 27 | Log.d("MainActivuty", BR.book1 + ""); 28 | } 29 | 30 | public void simpleSample(View view) { 31 | launchActivity(DataBindSimpleActivity.class); 32 | } 33 | 34 | public void observableSample(View view) { 35 | UpdateUserActivity.launch(this); 36 | } 37 | 38 | public void dataBindingList(View view) { 39 | GitHubContributorsActivity.launch(this); 40 | } 41 | 42 | public void elSample(View view) { 43 | ELActivity.launch(this); 44 | } 45 | 46 | 47 | public void converter(View view) { 48 | Intent intent = new Intent(this, ConverterActivity.class); 49 | startActivity(intent); 50 | } 51 | 52 | public void customSetter(View view) { 53 | Intent intent = new Intent(this, CustomSetterActivity.class); 54 | startActivity(intent); 55 | } 56 | 57 | public void searchDebounce(View view){ 58 | Intent intent = new Intent(this, SearchDebounceActivity.class); 59 | startActivity(intent); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/SearchDebounceActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import androidx.databinding.DataBindingUtil; 4 | import android.os.Bundle; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | 8 | import com.jakewharton.rxbinding.widget.RxTextView; 9 | import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent; 10 | import com.mvvm.R; 11 | import com.mvvm.adapter.SearchAdapter; 12 | import com.mvvm.databinding.SearchDebounceBinding; 13 | import com.mvvm.http.ApiServiceFactory; 14 | import com.mvvm.http.SearchApi; 15 | import com.mvvm.utils.DividerItemDecoration; 16 | import com.mvvm.utils.RecyclerViewUtils; 17 | 18 | import java.util.List; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | import rx.Observer; 22 | import rx.Subscription; 23 | import rx.android.schedulers.AndroidSchedulers; 24 | import rx.functions.Action1; 25 | import rx.schedulers.Schedulers; 26 | 27 | /** 28 | * Created by chiclaim on 2016/02/26 29 | */ 30 | public class SearchDebounceActivity extends BaseActivity { 31 | 32 | private SearchApi searchApi = ApiServiceFactory.createService(SearchApi.class); 33 | 34 | private SearchAdapter adapter; 35 | 36 | private Subscription subscription; 37 | 38 | @Override 39 | public void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | SearchDebounceBinding binding = DataBindingUtil.setContentView(this, 42 | R.layout.activity_search_debounce); 43 | 44 | adapter = new SearchAdapter(this); 45 | RecyclerViewUtils.setLinearManagerAndAdapter(binding.recyclerView, adapter); 46 | binding.recyclerView.addItemDecoration(DividerItemDecoration.newVertical(this, 47 | R.dimen.list_divider_height, R.color.divider_color)); 48 | 49 | //===========================@TODO 50 | //1,避免EditText没改变一次就请求一次. 51 | //2,避免频繁的请求,多个导致结果顺序错乱,最终的结果也就有问题. 52 | 53 | // 但是对于第二个问题,也不能彻底的解决. 比如停止输入400毫秒后, 54 | // 那么肯定会开始请求Search接口, 但是用户又会输入新的关键字, 55 | // 这个时候上个请求还没有返回, 新的请求又去请求Search接口. 56 | // 这个时候有可能最后的一个请求返回, 第一个请求最后返回,导致搜索结果不是想要的. 57 | //===========================@TODO 58 | 59 | subscription = RxTextView.textChangeEvents(binding.inputSearch) 60 | .debounce(400, TimeUnit.MILLISECONDS) 61 | .observeOn(AndroidSchedulers.mainThread()) 62 | .subscribe(getSearchObserver()); 63 | } 64 | 65 | 66 | private Observer getSearchObserver() { 67 | return new Observer() { 68 | @Override 69 | public void onCompleted() { 70 | Log.d("getSearchObserver", "--------- onComplete"); 71 | } 72 | 73 | @Override 74 | public void onError(Throwable e) { 75 | Log.d("getSearchObserver", e.getMessage()); 76 | } 77 | 78 | @Override 79 | public void onNext(TextViewTextChangeEvent onTextChangeEvent) { 80 | String key = onTextChangeEvent.text().toString(); 81 | Log.d("getSearchObserver", "--------- onNext:" + key); 82 | if (TextUtils.isEmpty(key)) { 83 | adapter.removeAll(); 84 | return; 85 | } 86 | searchApi.search(key) 87 | .observeOn(AndroidSchedulers.mainThread()) 88 | .subscribeOn(Schedulers.io()) 89 | .subscribe(new Action1>() { 90 | @Override 91 | public void call(List o) { 92 | adapter.removeAll(); 93 | adapter.appendItems(o); 94 | } 95 | }, new Action1() { 96 | @Override 97 | public void call(Throwable o) { 98 | o.printStackTrace(); 99 | } 100 | }); 101 | } 102 | }; 103 | } 104 | 105 | 106 | @Override 107 | protected void onDestroy() { 108 | super.onDestroy(); 109 | if (!subscription.isUnsubscribed()) { 110 | subscription.unsubscribe(); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/ui/UpdateUserActivity.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.ui; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import androidx.databinding.DataBindingUtil; 6 | import androidx.databinding.ObservableArrayMap; 7 | import android.os.Bundle; 8 | import androidx.appcompat.app.AppCompatActivity; 9 | import android.view.View; 10 | 11 | import com.mvvm.R; 12 | import com.mvvm.databinding.ActivityUpdateUserBinding; 13 | import com.mvvm.model.User; 14 | import com.mvvm.model.UserField; 15 | 16 | /** 17 | * Created by chiclaim on 2016/02/18 18 | */ 19 | public class UpdateUserActivity extends BaseActivity { 20 | private ActivityUpdateUserBinding binding; 21 | private User user; 22 | private UserField userField = new UserField(); 23 | private ObservableArrayMap map = new ObservableArrayMap(); 24 | 25 | public static void launch(Context context) { 26 | Intent intent = new Intent(context, UpdateUserActivity.class); 27 | context.startActivity(intent); 28 | } 29 | 30 | 31 | @Override 32 | public void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | binding = DataBindingUtil.setContentView(this, R.layout.activity_update_user); 35 | user = new User("Chiclaim", "119"); 36 | userField.realName.set("Chiclaim"); 37 | userField.mobile.set("119"); 38 | map.put("realName", "Chiclaim"); 39 | map.put("mobile", "119"); 40 | 41 | binding.setUser(user); 42 | binding.setFields(userField); 43 | binding.setCollection(map); 44 | } 45 | 46 | //如果(某个)字段发生变化. 47 | //1,通过User继承BaseObservable实现 48 | //2,通过ObservableField方式实现 49 | //3,通过Observable Collections的方式 如:ObservableArrayMap 50 | //4,当然可以通过binding.setUser(user) [相当于所有的View重新设置一遍] 51 | public void updateNameByPOJP(View view) { 52 | 53 | if ("Johnny".equals(user.getRealName())) { 54 | user.setRealName("Chiclaim"); 55 | user.setMobile("110"); 56 | } else { 57 | user.setRealName("Johnny"); 58 | user.setMobile("119"); 59 | } 60 | //当然可以通过binding.setUser(user) 61 | binding.setUser(user); 62 | } 63 | 64 | public void updateNameByField(View view) { 65 | if ("Johnny".equals(userField.realName.get())) { 66 | userField.realName.set("Chiclaim"); 67 | userField.mobile.set("110"); 68 | } else { 69 | userField.realName.set("Johnny"); 70 | userField.mobile.set("119"); 71 | } 72 | } 73 | 74 | public void updateNameByCollection(View view) { 75 | if ("Johnny".equals(map.get("realName"))) { 76 | map.put("realName", "Chiclaim"); 77 | map.put("mobile", "110"); 78 | } else { 79 | map.put("realName", "Johnny"); 80 | map.put("mobile", "119"); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/utils/CrashHandler.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.utils; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.pm.PackageInfo; 6 | import android.content.pm.PackageManager; 7 | import android.content.pm.PackageManager.NameNotFoundException; 8 | import android.os.Build; 9 | import android.os.Environment; 10 | import android.os.Looper; 11 | import android.util.Log; 12 | import android.widget.Toast; 13 | 14 | import java.io.BufferedReader; 15 | import java.io.File; 16 | import java.io.FileInputStream; 17 | import java.io.FileNotFoundException; 18 | import java.io.FileOutputStream; 19 | import java.io.IOException; 20 | import java.io.InputStreamReader; 21 | import java.io.PrintWriter; 22 | import java.io.StringWriter; 23 | import java.io.Writer; 24 | import java.lang.Thread.UncaughtExceptionHandler; 25 | import java.lang.reflect.Field; 26 | import java.text.DateFormat; 27 | import java.text.SimpleDateFormat; 28 | import java.util.Date; 29 | import java.util.HashMap; 30 | import java.util.Map; 31 | 32 | /** 33 | * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告. 34 | *

35 | *

36 | *

37 | * 需要在Application中注册,为了要在程序启动器就监控整个程序。 38 | */ 39 | public class CrashHandler implements UncaughtExceptionHandler { 40 | 41 | //public static final String DIR_PATH = "crash_log"; 42 | private String DIR_PATH; 43 | 44 | public static final String TAG = "CrashHandler"; 45 | // CrashHandler实例 46 | 47 | 48 | private static CrashHandler instance; 49 | // 系统默认的UncaughtException处理类 50 | 51 | 52 | private UncaughtExceptionHandler mDefaultHandler; 53 | // 程序的Context对象 54 | 55 | 56 | private Context mContext; 57 | // 用来存储设备信息和异常信息 58 | 59 | 60 | private Map infos = new HashMap(); 61 | 62 | // 用于格式化日期,作为日志文件名的一部分 63 | 64 | 65 | @SuppressLint("SimpleDateFormat") 66 | private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); 67 | 68 | /** 69 | * 保证只有一个CrashHandler实例 70 | */ 71 | private CrashHandler() { 72 | } 73 | 74 | /** 75 | * 获取CrashHandler实例 ,单例模式 76 | */ 77 | public static CrashHandler getInstance() { 78 | if (instance == null) 79 | instance = new CrashHandler(); 80 | return instance; 81 | } 82 | 83 | /** 84 | * 初始化 85 | */ 86 | public void init(Context context, String dirName) { 87 | DIR_PATH = dirName; 88 | mContext = context; 89 | // 获取系统默认的UncaughtException处理器 90 | 91 | 92 | mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); 93 | // 设置该CrashHandler为程序的默认处理器 94 | 95 | 96 | Thread.setDefaultUncaughtExceptionHandler(this); 97 | } 98 | 99 | /** 100 | * 当UncaughtException发生时会转入该函数来处理 101 | */ 102 | @Override 103 | public void uncaughtException(Thread thread, Throwable ex) { 104 | if (!handleException(ex) && mDefaultHandler != null) { 105 | // 如果用户没有处理则让系统默认的异常处理器来处理 106 | mDefaultHandler.uncaughtException(thread, ex); 107 | } else { 108 | try { 109 | Thread.sleep(1000); 110 | } catch (InterruptedException e) { 111 | Log.e(TAG, "error : ", e); 112 | } 113 | System.exit(0); 114 | android.os.Process.killProcess(android.os.Process.myPid()); 115 | } 116 | } 117 | 118 | /** 119 | * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 120 | * 121 | * @param ex 122 | * @return true:如果处理了该异常信息;否则返回false. 123 | */ 124 | private boolean handleException(Throwable ex) { 125 | if (ex == null) { 126 | return false; 127 | } 128 | // 收集设备参数信息 129 | 130 | 131 | collectDeviceInfo(mContext); 132 | 133 | // 使用Toast来显示异常信息 134 | 135 | 136 | new Thread() { 137 | @Override 138 | public void run() { 139 | Looper.prepare(); 140 | // Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", 141 | 142 | 143 | // Toast.LENGTH_SHORT).show(); 144 | 145 | 146 | Looper.loop(); 147 | } 148 | }.start(); 149 | // 保存日志文件 150 | 151 | 152 | saveCatchInfo2File(ex); 153 | return true; 154 | } 155 | 156 | /** 157 | * 收集设备参数信息 158 | * 159 | * @param ctx 160 | */ 161 | public void collectDeviceInfo(Context ctx) { 162 | try { 163 | PackageManager pm = ctx.getPackageManager(); 164 | PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); 165 | if (pi != null) { 166 | String versionName = pi.versionName == null ? "null" : pi.versionName; 167 | String versionCode = pi.versionCode + ""; 168 | infos.put("versionName", versionName); 169 | infos.put("versionCode", versionCode); 170 | } 171 | } catch (NameNotFoundException e) { 172 | Log.e(TAG, "an error occured when collect package info", e); 173 | } 174 | Field[] fields = Build.class.getDeclaredFields(); 175 | for (Field field : fields) { 176 | try { 177 | field.setAccessible(true); 178 | infos.put(field.getName(), field.get(null).toString()); 179 | Log.d(TAG, field.getName() + " : " + field.get(null)); 180 | } catch (Exception e) { 181 | Log.e(TAG, "an error occured when collect crash info", e); 182 | } 183 | } 184 | } 185 | 186 | /** 187 | * 保存错误信息到文件中 188 | * 189 | * @param ex 190 | * @return 返回文件名称, 便于将文件传送到服务器 191 | */ 192 | private String saveCatchInfo2File(Throwable ex) { 193 | StringBuffer sb = new StringBuffer(); 194 | for (Map.Entry entry : infos.entrySet()) { 195 | String key = entry.getKey(); 196 | String value = entry.getValue(); 197 | sb.append(key + "=" + value + "\n"); 198 | } 199 | 200 | Writer writer = new StringWriter(); 201 | PrintWriter printWriter = new PrintWriter(writer); 202 | ex.printStackTrace(printWriter); 203 | Throwable cause = ex.getCause(); 204 | while (cause != null) { 205 | cause.printStackTrace(printWriter); 206 | cause = cause.getCause(); 207 | } 208 | printWriter.close(); 209 | String result = writer.toString(); 210 | sb.append(result); 211 | FileOutputStream fos = null; 212 | try { 213 | long timestamp = System.currentTimeMillis(); 214 | String time = formatter.format(new Date()); 215 | String fileName = "crash-" + time + "-" + timestamp + ".log"; 216 | String savePath = getSavePath(mContext, DIR_PATH); 217 | fos = new FileOutputStream(new File(savePath, fileName)); 218 | fos.write(sb.toString().getBytes()); 219 | //sendCrashLog2PM(new File(savePath, fileName).getAbsolutePath()); 220 | fos.close(); 221 | return fileName; 222 | } catch (Exception e) { 223 | Log.e(TAG, "an error occured while writing file...", e); 224 | } finally { 225 | if (fos != null) { 226 | try { 227 | fos.close(); 228 | } catch (IOException e) { 229 | e.printStackTrace(); 230 | } 231 | } 232 | } 233 | return null; 234 | } 235 | 236 | /** 237 | * 如果没有外部存储,则使用内部存储 238 | * 239 | * @param context 240 | * @param subDir 241 | * @return 242 | */ 243 | public static String getSavePath(Context context, String subDir) { 244 | // 判断SD卡是否存在 245 | boolean sdCardExist = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); 246 | File file; 247 | if (sdCardExist) { 248 | file = Environment.getExternalStorageDirectory(); 249 | } else {// 内存存储空间 250 | file = context.getFilesDir(); 251 | return getPath(file, subDir); 252 | } 253 | return getPath(file, subDir); 254 | } 255 | 256 | private static String getPath(File f, String subDir) { 257 | File file = new File(f.getAbsolutePath() + File.separator + subDir); 258 | if (!file.exists()) { 259 | file.mkdirs(); 260 | } 261 | return file.getAbsolutePath(); 262 | } 263 | 264 | /** 265 | * 将捕获的导致崩溃的错误信息发送给开发人员 266 | *

267 | *

268 | *

269 | * 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。 270 | */ 271 | public void sendCrashLog2PM(String fileName) { 272 | if (!new File(fileName).exists()) { 273 | Toast.makeText(mContext, "日志文件不存在!", Toast.LENGTH_SHORT).show(); 274 | return; 275 | } 276 | FileInputStream fis = null; 277 | BufferedReader reader = null; 278 | String s = null; 279 | try { 280 | fis = new FileInputStream(fileName); 281 | reader = new BufferedReader(new InputStreamReader(fis, "GBK")); 282 | while (true) { 283 | s = reader.readLine(); 284 | if (s == null) 285 | break; 286 | // 由于目前尚未确定以何种方式发送,所以先打出log日志。 287 | 288 | 289 | Log.i("info", s.toString()); 290 | } 291 | } catch (FileNotFoundException e) { 292 | e.printStackTrace(); 293 | } catch (IOException e) { 294 | e.printStackTrace(); 295 | } finally { // 关闭流 296 | 297 | try { 298 | if (reader != null) 299 | reader.close(); 300 | if (fis != null) 301 | fis.close(); 302 | } catch (IOException e) { 303 | e.printStackTrace(); 304 | } 305 | } 306 | } 307 | } -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/utils/DividerItemDecoration.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.utils; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Rect; 6 | import android.graphics.drawable.ColorDrawable; 7 | import android.graphics.drawable.Drawable; 8 | import androidx.recyclerview.widget.LinearLayoutManager; 9 | import androidx.recyclerview.widget.RecyclerView; 10 | import android.view.View; 11 | 12 | public class DividerItemDecoration extends RecyclerView.ItemDecoration { 13 | public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; 14 | public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; 15 | private Drawable mDivider; 16 | 17 | private int mOrientation; 18 | private int mDividerHeight; 19 | 20 | private DividerItemDecoration() { 21 | } 22 | 23 | public static DividerItemDecoration newVertical(Context context, int dimenResId, int colorResId) { 24 | return new DividerItemDecoration(context, 25 | VERTICAL_LIST, 26 | context.getResources().getDimensionPixelSize(dimenResId), 27 | context.getResources().getColor(colorResId)); 28 | } 29 | 30 | public static DividerItemDecoration newHorizontal(Context context, int dimenResId, int colorResId) { 31 | return new DividerItemDecoration(context, 32 | HORIZONTAL_LIST, 33 | context.getResources().getDimensionPixelSize(dimenResId), 34 | context.getResources().getColor(colorResId)); 35 | } 36 | 37 | public DividerItemDecoration(Context context, int orientation, 38 | int dividerHeight, int color) { 39 | mDividerHeight = dividerHeight; 40 | mDivider = new ColorDrawable(color); 41 | setOrientation(orientation); 42 | } 43 | 44 | 45 | public void setOrientation(int orientation) { 46 | if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { 47 | throw new IllegalArgumentException("invalid orientation"); 48 | } 49 | mOrientation = orientation; 50 | } 51 | 52 | @Override 53 | public void onDraw(Canvas c, RecyclerView parent) { 54 | if (mOrientation == VERTICAL_LIST) { 55 | drawVertical(c, parent); 56 | } else { 57 | drawHorizontal(c, parent); 58 | } 59 | } 60 | 61 | public void drawVertical(Canvas c, RecyclerView parent) { 62 | final int left = parent.getPaddingLeft(); 63 | final int right = parent.getWidth() - parent.getPaddingRight(); 64 | 65 | final int childCount = parent.getChildCount(); 66 | for (int i = 0; i < childCount; i++) { 67 | final View child = parent.getChildAt(i); 68 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 69 | .getLayoutParams(); 70 | final int top = child.getBottom() + params.bottomMargin; 71 | final int bottom = top + mDividerHeight;//mDivider.getIntrinsicHeight(); 72 | 73 | mDivider.setBounds(left, top, right, bottom); 74 | mDivider.draw(c); 75 | } 76 | } 77 | 78 | public void drawHorizontal(Canvas c, RecyclerView parent) { 79 | final int top = parent.getPaddingTop(); 80 | final int bottom = parent.getHeight() - parent.getPaddingBottom(); 81 | 82 | final int childCount = parent.getChildCount(); 83 | for (int i = 0; i < childCount; i++) { 84 | final View child = parent.getChildAt(i); 85 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 86 | .getLayoutParams(); 87 | final int left = child.getRight() + params.rightMargin; 88 | final int right = left + mDividerHeight;//mDivider.getIntrinsicHeight(); 89 | 90 | mDivider.setBounds(left, top, right, bottom); 91 | mDivider.draw(c); 92 | } 93 | } 94 | 95 | @Override 96 | public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { 97 | if (mOrientation == VERTICAL_LIST) { 98 | outRect.set(0, 0, 0, mDividerHeight); 99 | } else { 100 | outRect.set(0, 0, mDividerHeight, 0); 101 | } 102 | } 103 | } -------------------------------------------------------------------------------- /app/src/main/java/com/mvvm/utils/RecyclerViewUtils.java: -------------------------------------------------------------------------------- 1 | package com.mvvm.utils; 2 | 3 | import androidx.recyclerview.widget.GridLayoutManager; 4 | import androidx.recyclerview.widget.LinearLayoutManager; 5 | import androidx.recyclerview.widget.RecyclerView; 6 | 7 | public class RecyclerViewUtils { 8 | 9 | public static final int HORIZONTAL = LinearLayoutManager.HORIZONTAL; 10 | public static final int VERTICAL = LinearLayoutManager.VERTICAL; 11 | 12 | private RecyclerViewUtils() { 13 | } 14 | 15 | 16 | public static void setLinearManagerAndAdapter(RecyclerView recyclerView, 17 | RecyclerView.Adapter adapter) { 18 | setLinearManagerAndAdapter(recyclerView, adapter, LinearLayoutManager.VERTICAL); 19 | } 20 | 21 | public static void setLinearManagerAndAdapter(RecyclerView recyclerView, 22 | RecyclerView.Adapter adapter, int orientation) { 23 | LinearLayoutManager linearLayoutManager = new LinearLayoutManager(recyclerView.getContext()); 24 | linearLayoutManager.setOrientation(orientation); 25 | recyclerView.setHasFixedSize(true); 26 | recyclerView.setLayoutManager(linearLayoutManager); 27 | recyclerView.setAdapter(adapter); 28 | } 29 | 30 | 31 | public static void setGridManagerAndAdapter(RecyclerView recyclerView, 32 | RecyclerView.Adapter adapter, int spanCount) { 33 | GridLayoutManager gridLayoutManager = new GridLayoutManager(recyclerView.getContext(), spanCount); 34 | gridLayoutManager.setOrientation(VERTICAL); 35 | recyclerView.setHasFixedSize(true); 36 | recyclerView.setLayoutManager(gridLayoutManager); 37 | recyclerView.setAdapter(adapter); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/erorr_loading.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chiclaim/AndroidDataBinding/af760c9f221dcd29838d9f57d70b75191050c359/app/src/main/res/drawable-xxhdpi/erorr_loading.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_like_yellow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chiclaim/AndroidDataBinding/af760c9f221dcd29838d9f57d70b75191050c359/app/src/main/res/drawable-xxhdpi/ic_like_yellow.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_like_yellowfull.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chiclaim/AndroidDataBinding/af760c9f221dcd29838d9f57d70b75191050c359/app/src/main/res/drawable-xxhdpi/ic_like_yellowfull.png -------------------------------------------------------------------------------- /app/src/main/res/drawable/placeholder_small_image.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/progress_medium_holo.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 25 | 26 | 27 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/shape_toast_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_converter.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 10 | 11 | 14 | 15 | 16 | 20 | 21 | 27 | 28 | 32 | 33 | 42 | 43 |