├── .github └── FUNDING.yml ├── LICENSE ├── README.md └── art └── logo.png /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://raw.githubusercontent.com/Blankj/AndroidUtilCode/master/art/donate.png 13 | -------------------------------------------------------------------------------- /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 2017 Blankj 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 | ![logo][logo] 2 | 3 | ## 摘要 4 | 5 | * [1 前言](#1-前言) 6 | * [2 AS 规范](#2-as-规范) 7 | * [3 命名规范](#3-命名规范) 8 | * [4 代码样式规范](#4-代码样式规范) 9 | * [5 资源文件规范](#5-资源文件规范) 10 | * [6 版本统一规范](#6-版本统一规范) 11 | * [7 第三方库规范](#7-第三方库规范) 12 | * [8 注释规范](#8-注释规范) 13 | * [9 测试规范](#9-测试规范) 14 | * [10 其他的一些规范](#10-其他的一些规范) 15 | 16 | 17 | ### 1 前言 18 | 19 | 为了有利于项目维护、增强代码可读性、提升 Code Review 效率以及规范团队安卓开发,故提出以下安卓开发规范,该规范结合本人多年的开发经验并吸取多家之精华,可谓是本人的呕心沥血之作,称其为当前最完善的安卓开发规范一点也不为过,如有更好建议,欢迎到 GitHub 提 issue,原文地址:**[Android 开发规范(完结版)][Android 开发规范(完结版)]**。相关 Demo,可以查看我的 Android 开发工具类集合项目:**[Android 开发人员不得不收集的代码][Android 开发人员不得不收集的代码]**。后续可能会根据该规范出一个 CheckStyle 插件来检查是否规范,当然也支持在 CI 上运行。 20 | 21 | 22 | ### 2 AS 规范 23 | 24 | 工欲善其事,必先利其器。 25 | 26 | 1. 尽量使用最新的稳定版的 IDE 进行开发; 27 | 2. 编码格式统一为 **UTF-8**; 28 | 3. 编辑完 .java、.xml 等文件后一定要 **格式化,格式化,格式化**(如果团队有公共的样式包,那就遵循它,否则统一使用 AS 默认模板即可); 29 | 4. 删除多余的 import,减少警告出现,可利用 AS 的 Optimize Imports(Settings -> Keymap -> Optimize Imports)快捷键; 30 | 5. Android 开发者工具可以参考这里:**[Android 开发者工具][Android 开发者工具]**; 31 | 32 | 33 | ### 3 命名规范 34 | 35 | 代码中的命名严禁使用拼音与英文混合的方式,更不允许直接使用中文的方式。正确的英文拼写和语法可以让阅读者易于理解,避免歧义。 36 | 37 | > 注意:即使纯拼音命名方式也要避免采用。但 `alibaba`、`taobao`、`youku`、`hangzhou` 等国际通用的名称,可视同英文。 38 | 39 | #### 3.1 包名 40 | 41 | 包名全部小写,连续的单词只是简单地连接起来,不使用下划线,采用反域名命名规则,全部使用小写字母。一级包名是顶级域名,通常为 `com`、`edu`、`gov`、`net`、`org` 等,二级包名为公司名,三级包名根据应用进行命名,后面就是对包名的划分了,关于包名的划分,推荐采用 PBF(按功能分包 Package By Feature),一开始我们采用的也是 PBL(按层分包 Package By Layer),很坑爹。PBF 可能不是很好区分在哪个功能中,不过也比 PBL 要好找很多,且 PBF 与 PBL 相比较有如下优势: 42 | 43 | * package 内高内聚,package 间低耦合 44 | 45 | 哪块要添新功能,只改某一个 package 下的东西。 46 | 47 | PBL 降低了代码耦合,但带来了 package 耦合,要添新功能,需要改 model、dbHelper、view、service 等等,需要改动好几个 package 下的代码,改动的地方越多,越容易产生新问题,不是吗? 48 | 49 | PBF 的话 featureA 相关的所有东西都在 featureA 包,feature 内高内聚、高度模块化,不同 feature 之间低耦合,相关的东西都放在一起,还好找。 50 | 51 | * package 有私有作用域(package-private scope) 52 | 53 | 你负责开发这块功能,这个目录下所有东西都是你的。 54 | 55 | PBL 的方式是把所有工具方法都放在 util 包下,小张开发新功能时候发现需要一个 xxUtil,但它又不是通用的,那应该放在哪里?没办法,按照分层原则,我们还得放在 util 包下,好像不太合适,但放在其它包更不合适,功能越来越多,util 类也越定义越多。后来小李负责开发一块功能时发现需要一个 xxUtil,同样不通用,去 util 包一看,怎么已经有了,而且还没法复用,只好放弃 xx 这个名字,改为 xxxUtil……,因为 PBL 的 package 没有私有作用域,每一个包都是 public(跨包方法调用是很平常的事情,每一个包对其它包来说都是可访问的);如果是 PBF,小张的 xxUtil 自然放在 featureA 下,小李的 xxUtil 在 featureB 下,如果觉得 util 好像是通用的,就去 util 包看看要不要把工具方法添进 xxUtil, class 命名冲突没有了。 56 | 57 | PBF 的 package 有私有作用域,featureA 不应该访问 featureB 下的任何东西(如果非访问不可,那就说明接口定义有问题)。 58 | 59 | * 很容易删除功能 60 | 61 | 统计发现新功能没人用,这个版本那块功能得去掉。 62 | 63 | 如果是 PBL,得从功能入口到整个业务流程把受到牵连的所有能删的代码和 class 都揪出来删掉,一不小心就完蛋。 64 | 65 | 如果是 PBF,好说,先删掉对应包,再删掉功能入口(删掉包后入口肯定报错了),完事。 66 | 67 | * 高度抽象 68 | 69 | 解决问题的一般方法是从抽象到具体,PBF 包名是对功能模块的抽象,包内的 class 是实现细节,符合从抽象到具体,而 PBL 弄反了。 70 | 71 | PBF 从确定 AppName 开始,根据功能模块划分 package,再考虑每块的具体实现细节,而 PBL 从一开始就要考虑要不要 dao 层,要不要 com 层等等。 72 | 73 | * 只通过 class 来分离逻辑代码 74 | 75 | PBL 既分离 class 又分离 package,而 PBF 只通过 class 来分离逻辑代码。 76 | 77 | 没有必要通过 package 分离,因为 PBL 中也可能出现尴尬的情况: 78 | 79 | ``` 80 | ├── service 81 | ├── MainService.java 82 | ``` 83 | 84 | 按照 PBL, service 包下的所有东西都是 Service,应该不需要 Service 后缀,但实际上通常为了方便,直接 import service 包,Service 后缀是为了避免引入的 class 和当前包下的 class 命名冲突,当然,不用后缀也可以,得写清楚包路径,比如 `new com.domain.service.MainService()`,麻烦;而 PBF 就很方便,无需 import,直接 `new MainService()` 即可。 85 | 86 | * package 的大小有意义了 87 | 88 | PBL 中包的大小无限增长是合理的,因为功能越添越多,而 PBF 中包太大(包里 class 太多)表示这块需要重构(划分子包)。 89 | 90 | 如要知道更多好处,可以查看这篇博文:**[Package by features, not layers][Package by features, not layers]**,当然,我们大谷歌也有相应的 Sample:**[todo-mvp][todo-mvp]**,其结构如下所示,很值得学习。 91 | 92 | ``` 93 | com 94 | └── example 95 | └── android 96 | └── architecture 97 | └── blueprints 98 | └── todoapp 99 | ├── BasePresenter.java 100 | ├── BaseView.java 101 | ├── addedittask 102 | │   ├── AddEditTaskActivity.java 103 | │   ├── AddEditTaskContract.java 104 | │   ├── AddEditTaskFragment.java 105 | │   └── AddEditTaskPresenter.java 106 | ├── data 107 | │   ├── Task.java 108 | │   └── source 109 | │   ├── TasksDataSource.java 110 | │   ├── TasksRepository.java 111 | │   ├── local 112 | │   │   ├── TasksDbHelper.java 113 | │   │   ├── TasksLocalDataSource.java 114 | │   │   └── TasksPersistenceContract.java 115 | │   └── remote 116 | │   └── TasksRemoteDataSource.java 117 | ├── statistics 118 | │   ├── StatisticsActivity.java 119 | │   ├── StatisticsContract.java 120 | │   ├── StatisticsFragment.java 121 | │   └── StatisticsPresenter.java 122 | ├── taskdetail 123 | │   ├── TaskDetailActivity.java 124 | │   ├── TaskDetailContract.java 125 | │   ├── TaskDetailFragment.java 126 | │   └── TaskDetailPresenter.java 127 | ├── tasks 128 | │   ├── ScrollChildSwipeRefreshLayout.java 129 | │   ├── TasksActivity.java 130 | │   ├── TasksContract.java 131 | │   ├── TasksFilterType.java 132 | │   ├── TasksFragment.java 133 | │   └── TasksPresenter.java 134 | └── util 135 | ├── ActivityUtils.java 136 | ├── EspressoIdlingResource.java 137 | └── SimpleCountingIdlingResource.java 138 | ``` 139 | 140 | 参考以上的代码结构,按功能分包具体可以这样做: 141 | 142 | ``` 143 | com 144 | └── domain 145 | └── app 146 | ├── App.java 定义 Application 类 147 | ├── Config.java 定义配置数据(常量) 148 | ├── base 基础组件 149 | ├── custom_view 自定义视图 150 | ├── data 数据处理 151 | │   ├── DataManager.java 数据管理器, 152 | │   ├── local 来源于本地的数据,比如 SP,Database,File 153 | │   ├── model 定义 model(数据结构以及 getter/setter、compareTo、equals 等等,不含复杂操作) 154 | │   └── remote 来源于远端的数据 155 | ├── feature 功能 156 | │   ├── feature0 功能 0 157 | │   │ ├── feature0Activity.java 158 | │   │ ├── feature0Fragment.java 159 | │ │ ├── xxAdapter.java 160 | │ │ └── ... 其他 class 161 | │ └── ...其他功能 162 | ├── injection 依赖注入 163 | ├── util 工具类 164 | └── widget 小部件 165 | ``` 166 | 167 | 168 | #### 3.2 类名 169 | 170 | 类名都以 `UpperCamelCase` 风格编写。 171 | 172 | 类名通常是名词或名词短语,接口名称有时可能是形容词或形容词短语。现在还没有特定的规则或行之有效的约定来命名注解类型。 173 | 174 | 名词,采用大驼峰命名法,尽量避免缩写,除非该缩写是众所周知的, 比如 HTML、URL,如果类名称中包含单词缩写,则单词缩写的每个字母均应大写。 175 | 176 | | 类 | 描述 | 例如 | 177 | | :-------------------- | :------------------------ | :--------------------------------------- | 178 | | `Activity` 类 | `Activity` 为后缀标识 | 欢迎页面类 `WelcomeActivity` | 179 | | `Adapter` 类 | `Adapter` 为后缀标识 | 新闻详情适配器 `NewsDetailAdapter` | 180 | | 解析类 | `Parser` 为后缀标识 | 首页解析类 `HomePosterParser` | 181 | | 工具方法类 | `Utils` 或 `Manager` 为后缀标识 | 线程池管理类:`ThreadPoolManager`
日志工具类:`LogUtils`(`Logger` 也可)
打印工具类:`PrinterUtils` | 182 | | 数据库类 | 以 `DBHelper` 后缀标识 | 新闻数据库:`NewsDBHelper` | 183 | | `Service` 类 | 以 `Service` 为后缀标识 | 时间服务 `TimeService` | 184 | | `BroadcastReceiver` 类 | 以 `Receiver` 为后缀标识 | 推送接收 `JPushReceiver` | 185 | | `ContentProvider` 类 | 以 `Provider` 为后缀标识 | `ShareProvider` | 186 | | 自定义的共享基础类 | 以 `Base` 开头 | `BaseActivity`, `BaseFragment` | 187 | 188 | 测试类的命名以它要测试的类的名称开始,以 Test 结束。例如:`HashTest` 或 `HashIntegrationTest`。 189 | 190 | 接口(interface):命名规则与类一样采用大驼峰命名法,多以 able 或 ible 结尾,如 `interface Runnable`、`interface Accessible`。 191 | 192 | > 注意:如果项目采用 MVP,所有 Model、View、Presenter 的接口都以 I 为前缀,不加后缀,其他的接口采用上述命名规则。 193 | 194 | 195 | #### 3.3 方法名 196 | 197 | 方法名都以 `lowerCamelCase` 风格编写。 198 | 199 | 方法名通常是动词或动词短语。 200 | 201 | | 方法 | 说明 | 202 | | :-------------------------- | ---------------------------------------- | 203 | | `initXX()` | 初始化相关方法,使用 init 为前缀标识,如初始化布局 `initView()` | 204 | | `isXX()`, `checkXX()` | 方法返回值为 boolean 型的请使用 is/check 为前缀标识 | 205 | | `getXX()` | 返回某个值的方法,使用 get 为前缀标识 | 206 | | `setXX()` | 设置某个属性值 | 207 | | `handleXX()`, `processXX()` | 对数据进行处理的方法 | 208 | | `displayXX()`, `showXX()` | 弹出提示框和提示信息,使用 display/show 为前缀标识 | 209 | | `updateXX()` | 更新数据 | 210 | | `saveXX()`, `insertXX()` | 保存或插入数据 | 211 | | `resetXX()` | 重置数据 | 212 | | `clearXX()` | 清除数据 | 213 | | `removeXX()`, `deleteXX()` | 移除数据或者视图等,如 `removeView()` | 214 | | `drawXX()` | 绘制数据或效果相关的,使用 draw 前缀标识 | 215 | 216 | 217 | #### 3.4 常量名 218 | 219 | 常量名命名模式为 `CONSTANT_CASE`,全部字母大写,用下划线分隔单词。那到底什么算是一个常量? 220 | 221 | 每个常量都是一个 `static final` 字段,但不是所有 `static final` 字段都是常量。在决定一个字段是否是一个常量时,得考虑它是否真的感觉像是一个常量。例如,如果观测任何一个该实例的状态是可变的,则它几乎肯定不会是一个常量。只是永远不打算改变的对象一般是不够的,它要真的一直不变才能将它示为常量。 222 | 223 | ```java 224 | // Constants 225 | static final int NUMBER = 5; 226 | static final ImmutableListNAMES = ImmutableList.of("Ed", "Ann"); 227 | static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable 228 | static final SomeMutableType[] EMPTY_ARRAY = {}; 229 | enum SomeEnum { ENUM_CONSTANT } 230 | 231 | // Not constants 232 | static String nonFinal = "non-final"; 233 | final String nonStatic = "non-static"; 234 | static final SetmutableCollection = new HashSet(); 235 | static final ImmutableSetmutableElements = ImmutableSet.of(mutable); 236 | static final Logger logger = Logger.getLogger(MyClass.getName()); 237 | static final String[] nonEmptyArray = {"these", "can", "change"}; 238 | ``` 239 | 240 | 241 | #### 3.5 非常量字段名 242 | 243 | 非常量字段名以 `lowerCamelCase` 风格的基础上改造为如下风格:基本结构为 `scope{Type0}VariableName{Type1}`、`type0VariableName{Type1}`、`variableName{Type1}`。 244 | 245 | 说明:`{}` 中的内容为可选。 246 | 247 | > 注意:所有的 VO(值对象)统一采用标准的 lowerCamelCase 风格编写,所有的 DTO(数据传输对象)就按照接口文档中定义的字段名编写。 248 | 249 | ##### 3.5.1 scope(范围) 250 | 251 | 非公有,非静态字段命名以 `m` 开头。 252 | 253 | 静态字段命名以 `s` 开头。 254 | 255 | 其他字段以小写字母开头。 256 | 257 | 例如: 258 | 259 | ```java 260 | public class MyClass { 261 | public int publicField; 262 | private static MyClass sSingleton; 263 | int mPackagePrivate; 264 | private int mPrivate; 265 | protected int mProtected; 266 | } 267 | ``` 268 | 269 | 使用 1 个字符前缀来表示作用范围,1 个字符的前缀必须小写,前缀后面是由表意性强的一个单词或多个单词组成的名字,而且每个单词的首写字母大写,其它字母小写,这样保证了对变量名能够进行正确的断句。 270 | 271 | 272 | ##### 3.5.2 Type0(控件类型) 273 | 274 | 考虑到 Android 众多的 UI 控件,为避免控件和普通成员变量混淆以及更好地表达意思,所有用来表示控件的成员变量统一加上控件缩写作为前缀(具体见附录 [UI 控件缩写表](#ui-控件缩写表))。 275 | 276 | 例如:`mIvAvatar`、`rvBooks`、`flContainer`。 277 | 278 | 279 | ##### 3.5.3 VariableName(变量名) 280 | 281 | 变量名中可能会出现量词,我们需要创建统一的量词,它们更容易理解,也更容易搜索。 282 | 283 | 例如:`mFirstBook`、`mPreBook`、`curBook`。 284 | 285 | | 量词列表 | 量词后缀说明 | 286 | | ------- | ---------- | 287 | | `First` | 一组变量中的第一个 | 288 | | `Last` | 一组变量中的最后一个 | 289 | | `Next` | 一组变量中的下一个 | 290 | | `Pre` | 一组变量中的上一个 | 291 | | `Cur` | 一组变量中的当前变量 | 292 | 293 | 294 | ##### 3.5.4 Type1(数据类型) 295 | 296 | 对于表示集合或者数组的非常量字段名,我们可以添加后缀来增强字段的可读性,比如: 297 | 298 | 集合添加如下后缀:List、Map、Set。 299 | 300 | 数组添加如下后缀:Arr。 301 | 302 | 例如:`mIvAvatarList`、`userArr`、`firstNameSet`。 303 | 304 | > 注意:如果数据类型不确定的话,比如表示的是很多书,那么使用其复数形式来表示也可,例如 `mBooks`。 305 | 306 | 307 | #### 3.6 参数名 308 | 309 | 参数名以 `lowerCamelCase` 风格编写,参数应该避免用单个字符命名。 310 | 311 | 312 | #### 3.7 局部变量名 313 | 314 | 局部变量名以 `lowerCamelCase` 风格编写,比起其它类型的名称,局部变量名可以有更为宽松的缩写。 315 | 316 | 虽然缩写更宽松,但还是要避免用单字符进行命名,除了临时变量和循环变量。 317 | 318 | 即使局部变量是 `final` 和不可改变的,也不应该把它示为常量,自然也不能用常量的规则去命名它。 319 | 320 | 321 | #### 3.8 临时变量 322 | 323 | 临时变量通常被取名为 `i`、`j`、`k`、`m` 和 `n`,它们一般用于整型;`c`、`d`、`e`,它们一般用于字符型。 如:`for (int i = 0; i < len; i++)`。 324 | 325 | 326 | #### 3.9 类型变量名 327 | 328 | 类型变量可用以下两种风格之一进行命名: 329 | 330 | 1. 单个的大写字母,后面可以跟一个数字(如:`E`, `T`, `X`, `T2`)。 331 | 2. 以类命名方式(参考[3.2 类名](#32-类名)),后面加个大写的 T(如:`RequestT`, `FooBarT`)。 332 | 333 | 更多还可参考:**[阿里巴巴 Java 开发手册][阿里巴巴 Java 开发手册]** 334 | 335 | 336 | ### 4 代码样式规范 337 | 338 | #### 4.1 使用标准大括号样式 339 | 340 | 左大括号不单独占一行,与其前面的代码位于同一行: 341 | 342 | ```java 343 | class MyClass { 344 | int func() { 345 | if (something) { 346 | // ... 347 | } else if (somethingElse) { 348 | // ... 349 | } else { 350 | // ... 351 | } 352 | } 353 | } 354 | ``` 355 | 356 | 我们需要在条件语句周围添加大括号。例外情况:如果整个条件语句(条件和主体)适合放在同一行,那么您可以(但不是必须)将其全部放在一行上。例如,我们接受以下样式: 357 | 358 | ```java 359 | if (condition) { 360 | body(); 361 | } 362 | ``` 363 | 364 | 同样也接受以下样式: 365 | 366 | ```java 367 | if (condition) body(); 368 | ``` 369 | 370 | 但不接受以下样式: 371 | 372 | ```java 373 | if (condition) 374 | body(); // bad! 375 | ``` 376 | 377 | 378 | #### 4.2 编写简短方法 379 | 380 | 在可行的情况下,尽量编写短小精炼的方法。我们了解,有些情况下较长的方法是恰当的,因此对方法的代码长度没有做出硬性限制。如果某个方法的代码超出 40 行,请考虑是否可以在不破坏程序结构的前提下对其拆解。 381 | 382 | 383 | #### 4.3 类成员的顺序 384 | 385 | 这并没有唯一的正确解决方案,但如果都使用一致的顺序将会提高代码的可读性,推荐使用如下排序: 386 | 387 | 1. 常量 388 | 2. 字段 389 | 3. 构造函数 390 | 4. 重写函数和回调 391 | 5. 公有函数 392 | 6. 私有函数 393 | 7. 内部类或接口 394 | 395 | 例如: 396 | 397 | ```java 398 | public class MainActivity extends Activity { 399 | 400 | private static final String TAG = MainActivity.class.getSimpleName(); 401 | 402 | private String mTitle; 403 | private TextView mTextViewTitle; 404 | 405 | @Override 406 | public void onCreate() { 407 | ... 408 | } 409 | 410 | public void setTitle(String title) { 411 | mTitle = title; 412 | } 413 | 414 | private void setUpView() { 415 | ... 416 | } 417 | 418 | static class AnInnerClass { 419 | 420 | } 421 | } 422 | ``` 423 | 424 | 如果类继承于 Android 组件(例如 `Activity` 或 `Fragment`),那么把重写函数按照他们的生命周期进行排序是一个非常好的习惯,例如,`Activity` 实现了 `onCreate()`、`onDestroy()`、`onPause()`、`onResume()`,它的正确排序如下所示: 425 | 426 | ```java 427 | public class MainActivity extends Activity { 428 | //Order matches Activity lifecycle 429 | @Override 430 | public void onCreate() {} 431 | 432 | @Override 433 | public void onResume() {} 434 | 435 | @Override 436 | public void onPause() {} 437 | 438 | @Override 439 | public void onDestroy() {} 440 | } 441 | ``` 442 | 443 | 444 | #### 4.4 函数参数的排序 445 | 446 | 在 Android 开发过程中,`Context` 在函数参数中是再常见不过的了,我们最好把 `Context` 作为其第一个参数。 447 | 448 | 正相反,我们把回调接口应该作为其最后一个参数。 449 | 450 | 例如: 451 | 452 | ```java 453 | // Context always goes first 454 | public User loadUser(Context context, int userId); 455 | 456 | // Callbacks always go last 457 | public void loadUserAsync(Context context, int userId, UserCallback callback); 458 | ``` 459 | 460 | 461 | #### 4.5 字符串常量的命名和值 462 | 463 | Android SDK 中的很多类都用到了键值对函数,比如 `SharedPreferences`、`Bundle`、`Intent`,所以,即便是一个小应用,我们最终也不得不编写大量的字符串常量。 464 | 465 | 当时用到这些类的时候,我们 **必须** 将它们的键定义为 `static final` 字段,并遵循以下指示作为前缀。 466 | 467 | | 类 | 字段名前缀 | 468 | | ------------------ | ----------- | 469 | | SharedPreferences | `PREF_` | 470 | | Bundle | `BUNDLE_` | 471 | | Fragment Arguments | `ARGUMENT_` | 472 | | Intent Extra | `EXTRA_` | 473 | | Intent Action | `ACTION_` | 474 | 475 | 说明:虽然 `Fragment.getArguments()` 得到的也是 `Bundle` ,但因为这是 `Bundle` 的常用用法,所以特意为此定义一个不同的前缀。 476 | 477 | 例如: 478 | 479 | ```java 480 | // 注意:字段的值与名称相同以避免重复问题 481 | static final String PREF_EMAIL = "PREF_EMAIL"; 482 | static final String BUNDLE_AGE = "BUNDLE_AGE"; 483 | static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID"; 484 | 485 | // 与意图相关的项使用完整的包名作为值的前缀 486 | static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME"; 487 | static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER"; 488 | ``` 489 | 490 | 491 | #### 4.6 Activities 和 Fragments 的传参 492 | 493 | 当 `Activity` 或 `Fragment` 传递数据通过 `Intent` 或 `Bundle` 时,不同值的键须遵循上一条所提及到的。 494 | 495 | 当 `Activity` 或 `Fragment` 启动需要传递参数时,那么它需要提供一个 `public static` 的函数来帮助启动或创建它。 496 | 497 | 这方面,AS 已帮你写好了相关的 Live Templates,启动相关 `Activity` 的只需要在其内部输入 `starter` 即可生成它的启动器,如下所示: 498 | 499 | ```java 500 | public static void start(Context context, User user) { 501 | Intent starter = new Intent(context, MainActivity.class); 502 | starter.putParcelableExtra(EXTRA_USER, user); 503 | context.startActivity(starter); 504 | } 505 | ``` 506 | 507 | 同理,启动相关 `Fragment` 在其内部输入 `newInstance` 即可,如下所示: 508 | 509 | ```java 510 | public static MainFragment newInstance(User user) { 511 | Bundle args = new Bundle(); 512 | args.putParcelable(ARGUMENT_USER, user); 513 | MainFragment fragment = new MainFragment(); 514 | fragment.setArguments(args); 515 | return fragment; 516 | } 517 | ``` 518 | 519 | > 注意:这些函数需要放在 `onCreate()` 之前的类的顶部;如果我们使用了这种方式,那么 `extras` 和 `arguments` 的键应该是 `private` 的,因为它们不再需要暴露给其他类来使用。 520 | 521 | 522 | #### 4.7 行长限制 523 | 524 | 代码中每一行文本的长度都应该不超过 100 个字符。虽然关于此规则存在很多争论,但最终决定仍是以 100 个字符为上限,如果行长超过了 100(AS 窗口右侧的竖线就是设置的行宽末尾 ),我们通常有两种方法来缩减行长。 525 | 526 | * 提取一个局部变量或方法(最好)。 527 | * 使用换行符将一行换成多行。 528 | 529 | 不过存在以下例外情况: 530 | 531 | * 如果备注行包含长度超过 100 个字符的示例命令或文字网址,那么为了便于剪切和粘贴,该行可以超过 100 个字符。 532 | * 导入语句行可以超出此限制,因为用户很少会看到它们(这也简化了工具编写流程)。 533 | 534 | ##### 4.7.1 换行策略 535 | 536 | 这没有一个准确的解决方案来决定如何换行,通常不同的解决方案都是有效的,但是有一些规则可以应用于常见的情况。 537 | 538 | ##### 4.7.1.1 操作符的换行 539 | 540 | 除赋值操作符之外,我们把换行符放在操作符之前,例如: 541 | 542 | ```java 543 | int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne 544 | + theFinalOne; 545 | ``` 546 | 547 | 赋值操作符的换行我们放在其后,例如: 548 | 549 | ```java 550 | int longName = 551 | anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne; 552 | ``` 553 | 554 | 555 | ##### 4.7.1.2 函数链的换行 556 | 557 | 当同一行中调用多个函数时(比如使用构建器时),对每个函数的调用应该在新的一行中,我们把换行符插入在 `.` 之前。 558 | 559 | 例如: 560 | 561 | ```java 562 | Picasso.with(context).load("https://blankj.com/images/avatar.jpg").into(ivAvatar); 563 | ``` 564 | 565 | 我们应该使用如下规则: 566 | 567 | ```java 568 | Picasso.with(context) 569 | .load("https://blankj.com/images/avatar.jpg") 570 | .into(ivAvatar); 571 | ``` 572 | 573 | 574 | ##### 4.7.1.3 多参数的换行 575 | 576 | 当一个方法有很多参数或者参数很长的时候,我们应该在每个 `,` 后面进行换行。 577 | 578 | 比如: 579 | 580 | ```java 581 | loadPicture(context, "https://blankj.com/images/avatar.jpg", ivAvatar, "Avatar of the user", clickListener); 582 | ``` 583 | 584 | 我们应该使用如下规则: 585 | 586 | ```java 587 | loadPicture(context, 588 | "https://blankj.com/images/avatar.jpg", 589 | ivAvatar, 590 | "Avatar of the user", 591 | clickListener); 592 | ``` 593 | 594 | 595 | ##### 4.7.1.4 RxJava 链式的换行 596 | 597 | RxJava 的每个操作符都需要换新行,并且把换行符插入在 `.` 之前。 598 | 599 | 例如: 600 | 601 | ```java 602 | public Observable syncLocations() { 603 | return mDatabaseHelper.getAllLocations() 604 | .concatMap(new Func1>() { 605 | @Override 606 | public Observable call(Location location) { 607 | return mRetrofitService.getLocation(location.id); 608 | } 609 | }) 610 | .retry(new Func2() { 611 | @Override 612 | public Boolean call(Integer numRetries, Throwable throwable) { 613 | return throwable instanceof RetrofitError; 614 | } 615 | }); 616 | } 617 | ``` 618 | 619 | 620 | ### 5 资源文件规范 621 | 622 | 资源文件命名为全部小写,采用下划线命名法。 623 | 624 | 如果是组件化开发,我们可以在组件和公共模块间创建一个 ui 模块来专门存放资源文件,然后让每个组件都依赖 ui 模块。这样做的好处是如果老项目要实现组件化的话,只需把资源文件都放入 ui 模块即可,如果想对资源文件进行分包,可以参考我这篇文章:**[Android Studio 下对资源进行分包][Android Studio 下对资源进行分包]**;还避免了多个模块间资源不能复用的问题。 625 | 626 | 如果是三方库开发,其使用到的资源文件及相关的 `name` 都应该使用库名作为前缀,这样做可以避免三方库资源和实际应用资源重名的冲突。 627 | 628 | #### 5.1 动画资源文件(anim/ 和 animator/) 629 | 630 | 安卓主要包含属性动画和视图动画,其视图动画包括补间动画和逐帧动画。属性动画文件需要放在 `res/animator/` 目录下,视图动画文件需放在 `res/anim/` 目录下。 631 | 632 | 命名规则:`{模块名_}逻辑名称`。 633 | 634 | 说明:`{}` 中的内容为可选,`逻辑名称` 可由多个单词加下划线组成。 635 | 636 | 例如:`refresh_progress.xml`、`market_cart_add.xml`、`market_cart_remove.xml`。 637 | 638 | 如果是普通的补间动画或者属性动画,可采用:`动画类型_方向` 的命名方式。 639 | 640 | 例如: 641 | 642 | | 名称 | 说明 | 643 | | ------------------- | ------- | 644 | | `fade_in` | 淡入 | 645 | | `fade_out` | 淡出 | 646 | | `push_down_in` | 从下方推入 | 647 | | `push_down_out` | 从下方推出 | 648 | | `push_left` | 推向左方 | 649 | | `slide_in_from_top` | 从头部滑动进入 | 650 | | `zoom_enter` | 变形进入 | 651 | | `slide_in` | 滑动进入 | 652 | | `shrink_to_middle` | 中间缩小 | 653 | 654 | 655 | #### 5.2 颜色资源文件(color/) 656 | 657 | 专门存放颜色相关的资源文件。 658 | 659 | 命名规则:`类型{_模块名}_逻辑名称`。 660 | 661 | 说明:`{}` 中的内容为可选。 662 | 663 | 例如:`sel_btn_font.xml`。 664 | 665 | 颜色资源也可以放于 `res/drawable/` 目录,引用时则用 `@drawable` 来引用,但不推荐这么做,最好还是把两者分开。 666 | 667 | 668 | #### 5.3 图片资源文件(drawable/ 和 mipmap/) 669 | 670 | `res/drawable/` 目录下放的是位图文件(.png、.9.png、.jpg、.gif)或编译为可绘制对象资源子类型的 XML 文件,而 `res/mipmap/` 目录下放的是不同密度的启动图标,所以 `res/mipmap/` 只用于存放启动图标,其余图片资源文件都应该放到 `res/drawable/` 目录下。 671 | 672 | 命名规则:`类型{_模块名}_逻辑名称`、`类型{_模块名}_颜色`。 673 | 674 | 说明:`{}` 中的内容为可选;`类型` 可以是[可绘制对象资源类型](可绘制对象资源类型),也可以是控件类型(具体见附录[UI 控件缩写表](#ui-控件缩写表));最后可加后缀 `_small` 表示小图,`_big` 表示大图。 675 | 676 | 例如: 677 | 678 | | 名称 | 说明 | 679 | | ------------------------- | ------------------------ | 680 | | `btn_main_about.png` | 主页关于按键 `类型_模块名_逻辑名称` | 681 | | `btn_back.png` | 返回按键 `类型_逻辑名称` | 682 | | `divider_maket_white.png` | 商城白色分割线 `类型_模块名_颜色` | 683 | | `ic_edit.png` | 编辑图标 `类型_逻辑名称` | 684 | | `bg_main.png` | 主页背景 `类型_逻辑名称` | 685 | | `btn_red.png` | 红色按键 `类型_颜色` | 686 | | `btn_red_big.png` | 红色大按键 `类型_颜色` | 687 | | `ic_head_small.png` | 小头像图标 `类型_逻辑名称` | 688 | | `bg_input.png` | 输入框背景 `类型_逻辑名称` | 689 | | `divider_white.png` | 白色分割线 `类型_颜色` | 690 | | `bg_main_head.png` | 主页头部背景 `类型_模块名_逻辑名称` | 691 | | `def_search_cell.png` | 搜索页面默认单元图片 `类型_模块名_逻辑名称` | 692 | | `ic_more_help.png` | 更多帮助图标 `类型_逻辑名称` | 693 | | `divider_list_line.png` | 列表分割线 `类型_逻辑名称` | 694 | | `sel_search_ok.xml` | 搜索界面确认选择器 `类型_模块名_逻辑名称` | 695 | | `shape_music_ring.xml` | 音乐界面环形形状 `类型_模块名_逻辑名称` | 696 | 697 | 如果有多种形态,如按钮选择器:`sel_btn_xx.xml`,采用如下命名: 698 | 699 | | 名称 | 说明 | 700 | | ----------------------- | ----------------------------- | 701 | | `sel_btn_xx` | 作用在 `btn_xx` 上的 `selector` | 702 | | `btn_xx_normal` | 默认状态效果 | 703 | | `btn_xx_pressed` | `state_pressed` 点击效果 | 704 | | `btn_xx_focused` | `state_focused` 聚焦效果 | 705 | | `btn_xx_disabled` | `state_enabled` 不可用效果 | 706 | | `btn_xx_checked` | `state_checked` 选中效果 | 707 | | `btn_xx_selected` | `state_selected` 选中效果 | 708 | | `btn_xx_hovered` | `state_hovered` 悬停效果 | 709 | | `btn_xx_checkable` | `state_checkable` 可选效果 | 710 | | `btn_xx_activated` | `state_activated` 激活效果 | 711 | | `btn_xx_window_focused` | `state_window_focused` 窗口聚焦效果 | 712 | 713 | > 注意:使用 Android Studio 的插件 SelectorChapek 可以快速生成 selector,前提是命名要规范。 714 | 715 | 716 | #### 5.4 布局资源文件(layout/) 717 | 718 | 命名规则:`类型_模块名`、`类型{_模块名}_逻辑名称`。 719 | 720 | 说明:`{}` 中的内容为可选。 721 | 722 | 例如: 723 | 724 | | 名称 | 说明 | 725 | | --------------------------- | --------------------------- | 726 | | `activity_main.xml` | 主窗体 `类型_模块名` | 727 | | `activity_main_head.xml` | 主窗体头部 `类型_模块名_逻辑名称` | 728 | | `fragment_music.xml` | 音乐片段 `类型_模块名` | 729 | | `fragment_music_player.xml` | 音乐片段的播放器 `类型_模块名_逻辑名称` | 730 | | `dialog_loading.xml` | 加载对话框 `类型_逻辑名称` | 731 | | `ppw_info.xml` | 信息弹窗(PopupWindow) `类型_逻辑名称` | 732 | | `item_main_song.xml` | 主页歌曲列表项 `类型_模块名_逻辑名称` | 733 | 734 | 735 | #### 5.5 菜单资源文件(menu/) 736 | 737 | 菜单相关的资源文件应放在该目录下。 738 | 739 | 命名规则:`{模块名_}逻辑名称` 740 | 741 | 说明:`{}` 中的内容为可选。 742 | 743 | 例如:`main_drawer.xml`、`navigation.xml`。 744 | 745 | 746 | #### 5.6 values 资源文件(values/) 747 | 748 | `values/` 资源文件下的文件都以 `s` 结尾,如 `attrs.xml`、`colors.xml`、`dimens.xml`,起作用的不是文件名称,而是 `` 标签下的各种标签,比如 ` 851 | ``` 852 | 853 | 应用到 `TextView` 中: 854 | 855 | ``` 856 | 862 | ``` 863 | 864 | 或许你需要为按钮控件做同样的事情,不要停止在那里,将一组相关的和重复 `android:xxxx` 的属性放到一个通用的 `