diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..750e8ac --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: https://raw.githubusercontent.com/Blankj/AndroidUtilCode/master/art/donate.png diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..99d8833 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Blankj + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 55be91c..c83b895 100755 --- a/README.md +++ b/README.md @@ -1,388 +1,224 @@ -# 安卓开发规范(updating) +![logo][logo] ## 摘要 * [1 前言](#1-前言) -* [2 AS规范](#2-as规范) +* [2 AS 规范](#2-as-规范) * [3 命名规范](#3-命名规范) -* [4 资源文件规范](#4-资源文件规范) -* [5 版本统一规范](#5-版本统一规范) -* [6 第三方库规范](#6-第三方库规范) -* [7 注释规范](#7-注释规范) -* [8 测试规范](#8-测试规范) -* [9 RN规范](#9-RN规范) +* [4 代码样式规范](#4-代码样式规范) +* [5 资源文件规范](#5-资源文件规范) +* [6 版本统一规范](#6-版本统一规范) +* [7 第三方库规范](#7-第三方库规范) +* [8 注释规范](#8-注释规范) +* [9 测试规范](#9-测试规范) * [10 其他的一些规范](#10-其他的一些规范) ### 1 前言 -为了利于项目维护以及规范开发,促进成员之间Code Review的效率,故提出以下开发规范,如有更好建议,欢迎到GitHub提issue,原文地址: **[安卓开发规范(updating)][安卓开发规范(updating)]** +为了有利于项目维护、增强代码可读性、提升 Code Review 效率以及规范团队安卓开发,故提出以下安卓开发规范,该规范结合本人多年的开发经验并吸取多家之精华,可谓是本人的呕心沥血之作,称其为当前最完善的安卓开发规范一点也不为过,如有更好建议,欢迎到 GitHub 提 issue,原文地址:**[Android 开发规范(完结版)][Android 开发规范(完结版)]**。相关 Demo,可以查看我的 Android 开发工具类集合项目:**[Android 开发人员不得不收集的代码][Android 开发人员不得不收集的代码]**。后续可能会根据该规范出一个 CheckStyle 插件来检查是否规范,当然也支持在 CI 上运行。 -### 2 AS规范 +### 2 AS 规范 工欲善其事,必先利其器。 -1. 尽量使用最新版的IDE进行开发; -2. 编码格式统一为**UTF-8**; -3. 编辑完`.java`、 `.xml`等文件后一定要**格式化**(基本格式方面使用 AS 默认模板即可); -4. 删除多余的import,减少警告出现,可利用AS的`Optimize Imports`(Settings → Keymap → Optimize Imports)快捷键; -5. AS常用开发插件可以参考这里~**[AS常用开发插件][AS常用开发插件]** +1. 尽量使用最新的稳定版的 IDE 进行开发; +2. 编码格式统一为 **UTF-8**; +3. 编辑完 .java、.xml 等文件后一定要 **格式化,格式化,格式化**(如果团队有公共的样式包,那就遵循它,否则统一使用 AS 默认模板即可); +4. 删除多余的 import,减少警告出现,可利用 AS 的 Optimize Imports(Settings -> Keymap -> Optimize Imports)快捷键; +5. Android 开发者工具可以参考这里:**[Android 开发者工具][Android 开发者工具]**; ### 3 命名规范 -代码中的命名严禁使用拼音与英文混合的方式,更不允许直接使用中文的方式。正确的英文拼写和语法可以让阅读者易于理解,避免歧义。 +代码中的命名严禁使用拼音与英文混合的方式,更不允许直接使用中文的方式。正确的英文拼写和语法可以让阅读者易于理解,避免歧义。 -> 注意:即使纯拼音命名方式也要避免采用。但`alibaba`、`taobao`、`youku`、`hangzhou`等国际通用的名称,可视同英文。 +> 注意:即使纯拼音命名方式也要避免采用。但 `alibaba`、`taobao`、`youku`、`hangzhou` 等国际通用的名称,可视同英文。 #### 3.1 包名 -包名全部小写,连续的单词只是简单地连接起来,不使用下划线,采用反域名命名规则,全部使用小写字母。一级包名是顶级域名,通常为`com`,`edu`,`gov`,`net`,`org`等,二级包名为公司名,三级包名根据应用进行命名,后面就是对包名的划分了,关于包名的划分,推荐使用按功能分,一开始我们也是按照层去分包的,很坑爹。按照功能分可能你不是很好区分在哪个功能中,不过也比你按照层区分要好找很多。具体可以参考这篇博文~**[Package by features, not layers][Package by features, not layers]**,当然,我们大谷歌也有相应的sample~**[iosched][iosched]**,其结构如下所示,很值得学习。 +包名全部小写,连续的单词只是简单地连接起来,不使用下划线,采用反域名命名规则,全部使用小写字母。一级包名是顶级域名,通常为 `com`、`edu`、`gov`、`net`、`org` 等,二级包名为公司名,三级包名根据应用进行命名,后面就是对包名的划分了,关于包名的划分,推荐采用 PBF(按功能分包 Package By Feature),一开始我们采用的也是 PBL(按层分包 Package By Layer),很坑爹。PBF 可能不是很好区分在哪个功能中,不过也比 PBL 要好找很多,且 PBF 与 PBL 相比较有如下优势: -``` -java -└─com - └─google - └─samples - └─apps - └─iosched - │ AppApplication.java 定义Application类 - │ Config.java 定义配置数据(常量) - │ - ├─about - │ AboutActivity.java - │ - ├─appwidget - │ ScheduleWidgetProvider.java - │ ScheduleWidgetRemoteViewsService.java - │ - ├─debug - │ │ DebugAction.java - │ │ DebugActivity.java - │ │ DebugFragment.java - │ │ - │ └─actions - │ DisplayUserDataDebugAction.java - │ ForceAppDataSyncNowAction.java - │ ForceSyncNowAction.java - │ ... - │ - ├─explore - │ │ ExploreIOActivity.java - │ │ ExploreIOFragment.java - │ │ ExploreModel.java - │ │ ... - │ │ - │ └─data - │ ItemGroup.java - │ LiveStreamData.java - │ MessageData.java - │ ... - │ - ├─feedback - │ FeedbackApiHelper.java - │ FeedbackConstants.java - │ FeedbackHelper.java - │ ... - │ - ├─framework - │ FragmentListener.java - │ LoaderIdlingResource.java - │ Model.java - │ ...定义interface并实现 - │ - ├─gcm - │ │ GCMCommand.java - │ │ GCMIntentService.java - │ │ GCMRedirectedBroadcastReceiver.java - │ │ ... - │ │ - │ └─command - │ AnnouncementCommand.java - │ NotificationCommand.java - │ SyncCommand.java - │ ... - │ - ├─io - │ │ BlocksHandler.java - │ │ HandlerException.java - │ │ HashtagsHandler.java - │ │ ...处理model - │ │ - │ ├─map - │ │ └─model - │ │ MapData.java - │ │ Marker.java - │ │ Tile.java - │ │ - │ └─model - │ Block.java - │ DataManifest.java - │ Hashtag.java - │ ... - │ - ├─map - │ │ InlineInfoFragment.java - │ │ MapActivity.java - │ │ MapFragment.java - │ │ ... - │ │ - │ └─util - │ CachedTileProvider.java - │ MarkerLoadingTask.java - │ MarkerModel.java - │ ... - │ - ├─model - │ ScheduleHelper.java - │ ScheduleItem.java - │ ScheduleItemHelper.java - │ ...定义model以及实现model相关操作 - │ - ├─myschedule - │ MyScheduleActivity.java - │ MyScheduleAdapter.java - │ MyScheduleFragment.java - │ ... - │ - ├─provider - │ ScheduleContract.java - │ ScheduleContractHelper.java - │ ScheduleDatabase.java - │ ...实现ContentProvider - │ (也在此处定义provider依赖的其它类,比如db操作) - │ - ├─receiver - │ SessionAlarmReceiver.java - │ - ├─service - │ DataBootstrapService.java - │ SessionAlarmService.java - │ SessionCalendarService.java - │ - ├─session - │ SessionDetailActivity.java - │ SessionDetailConstants.java - │ SessionDetailFragment.java - │ ... - │ - ├─settings - │ ConfMessageCardUtils.java - │ SettingsActivity.java - │ SettingsUtils.java - │ - ├─social - │ SocialActivity.java - │ SocialFragment.java - │ SocialModel.java - │ - ├─sync - │ │ ConferenceDataHandler.java - │ │ RemoteConferenceDataFetcher.java - │ │ SyncAdapter.java - │ │ ... - │ │ - │ └─userdata - │ │ AbstractUserDataSyncHelper.java - │ │ OnSuccessListener.java - │ │ UserAction.java - │ │ ... - │ │ - │ ├─gms - │ │ DriveHelper.java - │ │ GMSUserDataSyncHelper.java - │ │ - │ └─util - │ UserActionHelper.java - │ UserDataHelper.java - │ - ├─ui - │ │ BaseActivity.java - │ │ CheckableLinearLayout.java - │ │ SearchActivity.java - │ │ ...BaseActivity以及自定义UI组件 - │ │ - │ └─widget - │ AspectRatioView.java - │ BakedBezierInterpolator.java - │ BezelImageView.java - │ ...自定义小UI控件 - │ - ├─util - │ AboutUtils.java - │ AccountUtils.java - │ AnalyticsHelper.java - │ ...工具类,提供静态方法 - │ - ├─videolibrary - │ VideoLibraryActivity.java - │ VideoLibraryFilteredActivity.java - │ VideoLibraryFilteredFragment.java - │ ... - │ - └─welcome - AccountFragment.java - AttendingFragment.java - ConductFragment.java - ... -``` +* package 内高内聚,package 间低耦合 -参考Google I/O 2015的代码结构,按功能分包具体可以这样做: + 哪块要添新功能,只改某一个 package 下的东西。 -``` -src -└─com - └─domain - └─app - │ AppApplication.java 定义Application类 - │ Config.java 定义配置数据(常量) - │ - ├─framework - │ 定义interface以及相关基类 - │ - ├─io - │ 数据定义(model)、数据操作(比如json解析,但不包括db操作) - │ - ├─model - │ 定义model(数据结构以及getter/setter、compareTo、equals等等,不含复杂操作) - │ 以及modelHelper(提供便于操作model的api) - │ - ├─provider - │ 实现ContentProvider,及其依赖的db操作 - │ - ├─receiver - │ 实现Receiver - │ - ├─service - │ 实现Service(比如IntentService),用于在独立线程中异步do stuff - │ - ├─ui - │ 实现BaseActivity,以及自定义view和widget,相关的Adapter也放这里 - │ - ├─util - │ 实现工具类,提供静态方法 - │ - ├─feature1 - │ Item.java 定义model - │ ItemHelper.java 实现modelHelper - │ feature1Activity.java 定义UI - │ feature1DAO.java 私有db操作 - │ feature1Utils.java 私有工具函数 - │ ...其它私有class - │ - ├─...其它feature -``` + PBL 降低了代码耦合,但带来了 package 耦合,要添新功能,需要改 model、dbHelper、view、service 等等,需要改动好几个 package 下的代码,改动的地方越多,越容易产生新问题,不是吗? -PBF(按功能分包Package By Feature)与PBL(按层分包Package By Layer)相比较有如下优势: + PBF 的话 featureA 相关的所有东西都在 featureA 包,feature 内高内聚、高度模块化,不同 feature 之间低耦合,相关的东西都放在一起,还好找。 -* package内高内聚,package间低耦合 +* package 有私有作用域(package-private scope) -哪块要添新功能,只改某一个package下的东西 + 你负责开发这块功能,这个目录下所有东西都是你的。 -按class职能分层(PBL)降低了代码耦合,但带来了package耦合,要添新功能,需要改model、dbHelper、view、service等等,需要改动好几个package下的代码,改动的地方越多,越容易产生新问题,不是吗? + PBL 的方式是把所有工具方法都放在 util 包下,小张开发新功能时候发现需要一个 xxUtil,但它又不是通用的,那应该放在哪里?没办法,按照分层原则,我们还得放在 util 包下,好像不太合适,但放在其它包更不合适,功能越来越多,util 类也越定义越多。后来小李负责开发一块功能时发现需要一个 xxUtil,同样不通用,去 util 包一看,怎么已经有了,而且还没法复用,只好放弃 xx 这个名字,改为 xxxUtil……,因为 PBL 的 package 没有私有作用域,每一个包都是 public(跨包方法调用是很平常的事情,每一个包对其它包来说都是可访问的);如果是 PBF,小张的 xxUtil 自然放在 featureA 下,小李的 xxUtil 在 featureB 下,如果觉得 util 好像是通用的,就去 util 包看看要不要把工具方法添进 xxUtil, class 命名冲突没有了。 -按功能分包(PBF),featureA相关的所有东西都在featureA包,feature内高内聚高度模块化,不同feature之间低耦合,相关的东西都放在一起,还好找 + PBF 的 package 有私有作用域,featureA 不应该访问 featureB 下的任何东西(如果非访问不可,那就说明接口定义有问题)。 -* package有私有作用域(package-private scope) +* 很容易删除功能 -你负责开发这块功能,这个目录下所有东西都是你的 + 统计发现新功能没人用,这个版本那块功能得去掉。 -PBL的方式是把所有工具方法都放在util包下,小张开发新功能时候发现需要一个xxUtil,但它又不是通用的,那应该放在哪里?没办法,按照分层原则,我们还得放在util包下,好像不太合适,但放在其它包更不合适,功能越来越多,util类也越定义越多。后来小李负责开发一块功能时发现需要一个xxUtil,同样不通用,去util包一看,怎么已经有了,而且还没法复用,只好放弃xx这个名字,改为xxxUtil……因为PBL的package没有私有作用域,每一个包都是public(跨包方法调用是很平常的事情,每一个包对其它包来说都是可访问的) + 如果是 PBL,得从功能入口到整个业务流程把受到牵连的所有能删的代码和 class 都揪出来删掉,一不小心就完蛋。 -如果是PBF,小张的xxUtil自然放在feautreA下,小李的xxUtil在featureB下,如果觉得util好像是通用的,就去util包看看要不要把工具方法添进xxUtil,class命名冲突没有了 + 如果是 PBF,好说,先删掉对应包,再删掉功能入口(删掉包后入口肯定报错了),完事。 -PBF的package有私有作用域,featureA不应该访问featureB下的任何东西(如果非访问不可,那就说明接口定义有问题) +* 高度抽象 -* 很容易删除功能 + 解决问题的一般方法是从抽象到具体,PBF 包名是对功能模块的抽象,包内的 class 是实现细节,符合从抽象到具体,而 PBL 弄反了。 -统计发现新功能没人用,这个版本那块功能得去掉 + PBF 从确定 AppName 开始,根据功能模块划分 package,再考虑每块的具体实现细节,而 PBL 从一开始就要考虑要不要 dao 层,要不要 com 层等等。 -如果是PBL,得从功能入口到整个业务流程把受到牵连的所有能删的代码和class都揪出来删掉,一不小心就完蛋 +* 只通过 class 来分离逻辑代码 -如果是PBF,好说,先删掉对应包,再删掉功能入口(删掉包后入口肯定报错了),完事 + PBL 既分离 class 又分离 package,而 PBF 只通过 class 来分离逻辑代码。 -* 高度抽象 + 没有必要通过 package 分离,因为 PBL 中也可能出现尴尬的情况: -解决问题的一般方法是从抽象到具体,PBF包名是对功能模块的抽象,包内的class是实现细节,符合从抽象到具体,而PBL弄反了 + ``` + ├── service + ├── MainService.java + ``` -PBF从确定AppName开始,根据功能模块划分package,再考虑每块的具体实现细节,而PBL从一开始就要考虑要不要dao层,要不要com层等等 + 按照 PBL, service 包下的所有东西都是 Service,应该不需要 Service 后缀,但实际上通常为了方便,直接 import service 包,Service 后缀是为了避免引入的 class 和当前包下的 class 命名冲突,当然,不用后缀也可以,得写清楚包路径,比如 `new com.domain.service.MainService()`,麻烦;而 PBF 就很方便,无需 import,直接 `new MainService()` 即可。 -* 只通过class来分离逻辑代码 +* package 的大小有意义了 -PBL既分离class又分离package,而PBF只通过class来分离逻辑代码 + PBL 中包的大小无限增长是合理的,因为功能越添越多,而 PBF 中包太大(包里 class 太多)表示这块需要重构(划分子包)。 -没有必要通过package分离,因为PBL中也可能出现尴尬的情况: +如要知道更多好处,可以查看这篇博文:**[Package by features, not layers][Package by features, not layers]**,当然,我们大谷歌也有相应的 Sample:**[todo-mvp][todo-mvp]**,其结构如下所示,很值得学习。 ``` -├─service - │ MainServ.java +com +└── example + └── android + └── architecture + └── blueprints + └── todoapp + ├── BasePresenter.java + ├── BaseView.java + ├── addedittask + │   ├── AddEditTaskActivity.java + │   ├── AddEditTaskContract.java + │   ├── AddEditTaskFragment.java + │   └── AddEditTaskPresenter.java + ├── data + │   ├── Task.java + │   └── source + │   ├── TasksDataSource.java + │   ├── TasksRepository.java + │   ├── local + │   │   ├── TasksDbHelper.java + │   │   ├── TasksLocalDataSource.java + │   │   └── TasksPersistenceContract.java + │   └── remote + │   └── TasksRemoteDataSource.java + ├── statistics + │   ├── StatisticsActivity.java + │   ├── StatisticsContract.java + │   ├── StatisticsFragment.java + │   └── StatisticsPresenter.java + ├── taskdetail + │   ├── TaskDetailActivity.java + │   ├── TaskDetailContract.java + │   ├── TaskDetailFragment.java + │   └── TaskDetailPresenter.java + ├── tasks + │   ├── ScrollChildSwipeRefreshLayout.java + │   ├── TasksActivity.java + │   ├── TasksContract.java + │   ├── TasksFilterType.java + │   ├── TasksFragment.java + │   └── TasksPresenter.java + └── util + ├── ActivityUtils.java + ├── EspressoIdlingResource.java + └── SimpleCountingIdlingResource.java ``` -按照PBL,service包下的所有东西都是Controller,应该不需要Serv后缀,但实际上通常为了码起来方便,直接import service包,Serv后缀是为了避免引入的class和当前包下的class命名冲突,当然,不用后缀也可以,得写清楚包路径,比如new net.ayqy.service.Main(),麻烦 - -而PBF就很方便,无需import,直接new MainServ()即可 +参考以上的代码结构,按功能分包具体可以这样做: -* package的大小有意义了 - -PBL中包的大小无限增长是合理的,因为功能越添越多 +``` +com +└── domain + └── app + ├── App.java 定义 Application 类 + ├── Config.java 定义配置数据(常量) + ├── base 基础组件 + ├── custom_view 自定义视图 + ├── data 数据处理 + │   ├── DataManager.java 数据管理器, + │   ├── local 来源于本地的数据,比如 SP,Database,File + │   ├── model 定义 model(数据结构以及 getter/setter、compareTo、equals 等等,不含复杂操作) + │   └── remote 来源于远端的数据 + ├── feature 功能 + │   ├── feature0 功能 0 + │   │ ├── feature0Activity.java + │   │ ├── feature0Fragment.java + │ │ ├── xxAdapter.java + │ │ └── ... 其他 class + │ └── ...其他功能 + ├── injection 依赖注入 + ├── util 工具类 + └── widget 小部件 +``` -而PBF中包太大(包里class太多)表示这块需要重构(划分子包) #### 3.2 类名 -类名都以`UpperCamelCase`风格编写。 +类名都以 `UpperCamelCase` 风格编写。 类名通常是名词或名词短语,接口名称有时可能是形容词或形容词短语。现在还没有特定的规则或行之有效的约定来命名注解类型。 -名词,采用大驼峰命名法,尽量避免缩写,除非该缩写是众所周知的, 比如`HTML`, `URL`,如果类名称中包含单词缩写,则单词缩写的每个字母均应大写。 +名词,采用大驼峰命名法,尽量避免缩写,除非该缩写是众所周知的, 比如 HTML、URL,如果类名称中包含单词缩写,则单词缩写的每个字母均应大写。 -| 类 | 描述 | 例如 | -| :----------------- | :--------------------------------------- | :--------------------------------------- | -| Activity 类 | Activity为后缀标识 | 欢迎页面类WelcomeActivity | -| Adapter类 | Adapter 为后缀标识 | 新闻详情适配器 NewDetailAdapter | -| 解析类 | Parser为后缀标识 | 首页解析类HomePosterParser | -| 工具方法类 | Utils或Manager为后缀标识(与系统或第三方的Utils区分)或功能+Utils | 线程池管理类:ThreadPoolManager日志工具类:LogUtils(Logger也可)打印工具类:PrinterUtils | -| 数据库类 | 以DBHelper后缀标识 | 新闻数据库:NewDBHelper | -| Service类 | 以Service为后缀标识 | 时间服务TimeService | -| BroadcastReceiver类 | 以Receiver为后缀标识 | 推送接收JPushReceiver | -| ContentProvider类 | 以Provider为后缀标识 | ShareProvider | -| 自定义的共享基础类 | 以Base开头 | BaseActivity,BaseFragment | +| 类 | 描述 | 例如 | +| :-------------------- | :------------------------ | :--------------------------------------- | +| `Activity` 类 | `Activity` 为后缀标识 | 欢迎页面类 `WelcomeActivity` | +| `Adapter` 类 | `Adapter` 为后缀标识 | 新闻详情适配器 `NewsDetailAdapter` | +| 解析类 | `Parser` 为后缀标识 | 首页解析类 `HomePosterParser` | +| 工具方法类 | `Utils` 或 `Manager` 为后缀标识 | 线程池管理类:`ThreadPoolManager`
日志工具类:`LogUtils`(`Logger` 也可)
打印工具类:`PrinterUtils` | +| 数据库类 | 以 `DBHelper` 后缀标识 | 新闻数据库:`NewsDBHelper` | +| `Service` 类 | 以 `Service` 为后缀标识 | 时间服务 `TimeService` | +| `BroadcastReceiver` 类 | 以 `Receiver` 为后缀标识 | 推送接收 `JPushReceiver` | +| `ContentProvider` 类 | 以 `Provider` 为后缀标识 | `ShareProvider` | +| 自定义的共享基础类 | 以 `Base` 开头 | `BaseActivity`, `BaseFragment` | -测试类的命名以它要测试的类的名称开始,以Test结束。例如:`HashTest`或`HashIntegrationTest`。 +测试类的命名以它要测试的类的名称开始,以 Test 结束。例如:`HashTest` 或 `HashIntegrationTest`。 -接口(interface):命名规则与类一样采用大驼峰命名法,多以able或ible结尾,如 -`interface Runnable`、`interface Accessible`。 +接口(interface):命名规则与类一样采用大驼峰命名法,多以 able 或 ible 结尾,如 `interface Runnable`、`interface Accessible`。 -> 注意:如果项目采用MVP,所有Model、View、Presenter的接口都以I为前缀,不加后缀,其他的接口采用上述命名规则。 +> 注意:如果项目采用 MVP,所有 Model、View、Presenter 的接口都以 I 为前缀,不加后缀,其他的接口采用上述命名规则。 #### 3.3 方法名 -方法名都以`lowerCamelCase`风格编写。 +方法名都以 `lowerCamelCase` 风格编写。 方法名通常是动词或动词短语。 -| 方法 | 说明 | -| :--------------------- | ------------------------------------ | -| initXX() | 初始化相关方法,使用init为前缀标识,如初始化布局initView() | -| isXX() checkXX() | 方法返回值为boolean型的请使用is或check为前缀标识 | -| getXX() | 返回某个值的方法,使用get为前缀标识 | -| setXX() | 设置某个属性值 | -| handleXX()/processXX() | 对数据进行处理的方法 | -| displayXX()/showXX() | 弹出提示框和提示信息,使用display/show为前缀标识 | -| updateXX() | 更新数据 | -| saveXX() | 保存数据 | -| resetXX() | 重置数据 | -| clearXX() | 清除数据 | -| removeXX() | 移除数据或者视图等,如removeView(); | -| drawXX() | 绘制数据或效果相关的,使用draw前缀标识 | +| 方法 | 说明 | +| :-------------------------- | ---------------------------------------- | +| `initXX()` | 初始化相关方法,使用 init 为前缀标识,如初始化布局 `initView()` | +| `isXX()`, `checkXX()` | 方法返回值为 boolean 型的请使用 is/check 为前缀标识 | +| `getXX()` | 返回某个值的方法,使用 get 为前缀标识 | +| `setXX()` | 设置某个属性值 | +| `handleXX()`, `processXX()` | 对数据进行处理的方法 | +| `displayXX()`, `showXX()` | 弹出提示框和提示信息,使用 display/show 为前缀标识 | +| `updateXX()` | 更新数据 | +| `saveXX()`, `insertXX()` | 保存或插入数据 | +| `resetXX()` | 重置数据 | +| `clearXX()` | 清除数据 | +| `removeXX()`, `deleteXX()` | 移除数据或者视图等,如 `removeView()` | +| `drawXX()` | 绘制数据或效果相关的,使用 draw 前缀标识 | + #### 3.4 常量名 -常量名命名模式为`CONSTANT_CASE`,全部字母大写,用下划线分隔单词。那,到底什么算是一个常量? +常量名命名模式为 `CONSTANT_CASE`,全部字母大写,用下划线分隔单词。那到底什么算是一个常量? -每个常量都是一个静态`final`字段,但不是所有静态`final`字段都是常量。在决定一个字段是否是一个常量时,考虑它是否真的感觉像是一个常量。例如,如果任何一个该实例的观测状态是可变的,则它几乎肯定不会是一个常量。只是永远不打算改变对象一般是不够的,它要真的一直不变才能将它示为常量。 +每个常量都是一个 `static final` 字段,但不是所有 `static final` 字段都是常量。在决定一个字段是否是一个常量时,得考虑它是否真的感觉像是一个常量。例如,如果观测任何一个该实例的状态是可变的,则它几乎肯定不会是一个常量。只是永远不打算改变的对象一般是不够的,它要真的一直不变才能将它示为常量。 ```java // Constants @@ -404,221 +240,518 @@ static final String[] nonEmptyArray = {"these", "can", "change"}; #### 3.5 非常量字段名 -非常量字段名以`lowerCamelCase`风格的基础上改造为如下风格:基本结构为`scopeVariableNameType`。 +非常量字段名以 `lowerCamelCase` 风格的基础上改造为如下风格:基本结构为 `scope{Type0}VariableName{Type1}`、`type0VariableName{Type1}`、`variableName{Type1}`。 + +说明:`{}` 中的内容为可选。 -**scope:范围** +> 注意:所有的 VO(值对象)统一采用标准的 lowerCamelCase 风格编写,所有的 DTO(数据传输对象)就按照接口文档中定义的字段名编写。 -非公有,非静态字段命名以m开头。 +##### 3.5.1 scope(范围) -静态字段命名以s开头。 +非公有,非静态字段命名以 `m` 开头。 -公有非静态字段命名以p开头。 +静态字段命名以 `s` 开头。 -公有静态字段(全局变量)命名以g开头。 +其他字段以小写字母开头。 -例子: +例如: ```java public class MyClass { - int mPackagePrivate; - private int mPrivate; - protected int mProtected; - private static MyClass sSingleton; - public int pField; - public static int gField; + public int publicField; + private static MyClass sSingleton; + int mPackagePrivate; + private int mPrivate; + protected int mProtected; } ``` -使用1字符前缀来表示作用范围,1个字符的前缀必须小写,前缀后面是由表意性强的一个单词或多个单词组成的名字,而且每个单词的首写字母大写,其它字母小写,这样保证了对变量名能够进行正确的断句。 +使用 1 个字符前缀来表示作用范围,1 个字符的前缀必须小写,前缀后面是由表意性强的一个单词或多个单词组成的名字,而且每个单词的首写字母大写,其它字母小写,这样保证了对变量名能够进行正确的断句。 + + +##### 3.5.2 Type0(控件类型) + +考虑到 Android 众多的 UI 控件,为避免控件和普通成员变量混淆以及更好地表达意思,所有用来表示控件的成员变量统一加上控件缩写作为前缀(具体见附录 [UI 控件缩写表](#ui-控件缩写表))。 + +例如:`mIvAvatar`、`rvBooks`、`flContainer`。 + + +##### 3.5.3 VariableName(变量名) -**Type:类型** +变量名中可能会出现量词,我们需要创建统一的量词,它们更容易理解,也更容易搜索。 -考虑到Android中使用很多UI控件,为避免控件和普通成员变量混淆以及更好达意,所有用来表示控件的成员变量统一加上控件缩写作为后缀(文末附有缩写表)。 +例如:`mFirstBook`、`mPreBook`、`curBook`。 -对于普通变量一般不添加类型后缀,如果统一添加类型后缀,请参考文末的缩写表。 +| 量词列表 | 量词后缀说明 | +| ------- | ---------- | +| `First` | 一组变量中的第一个 | +| `Last` | 一组变量中的最后一个 | +| `Next` | 一组变量中的下一个 | +| `Pre` | 一组变量中的上一个 | +| `Cur` | 一组变量中的当前变量 | -用统一的量词通过在结尾处放置一个量词,就可创建更加统一的变量,它们更容易理解,也更容易搜索。 -> 注意:如果项目中使用`ButterKnife`,则不添加m前缀,以`lowerCamelCase`风格命名。 +##### 3.5.4 Type1(数据类型) -例如,请使用`mCustomerStrFirst`和`mCustomerStrLast`,而不要使用`mFirstCustomerStr`和`mLastCustomerStr`。 +对于表示集合或者数组的非常量字段名,我们可以添加后缀来增强字段的可读性,比如: -| 量词列表 | 量词后缀说明 | -| ----- | ----------- | -| First | 一组变量中的第一个 | -| Last | 一组变量中的最后一个 | -| Next | 一组变量中的下一个变量 | -| Prev | 一组变量中的上一个 | -| Cur | 一组变量中的当前变量 | +集合添加如下后缀:List、Map、Set。 -说明: +数组添加如下后缀:Arr。 -集合添加如下后缀:List、Map、Set -数组添加如下后缀:Arr +例如:`mIvAvatarList`、`userArr`、`firstNameSet`。 -> 注意:所有的VO(值对象)统一采用标准的lowerCamelCase风格编写,所有的DTO(数据传输对象)就按照接口文档中定义的字段名编写。 +> 注意:如果数据类型不确定的话,比如表示的是很多书,那么使用其复数形式来表示也可,例如 `mBooks`。 #### 3.6 参数名 -参数名以`lowerCamelCase`风格编写。 -参数应该避免用单个字符命名。 +参数名以 `lowerCamelCase` 风格编写,参数应该避免用单个字符命名。 #### 3.7 局部变量名 -局部变量名以`lowerCamelCase`风格编写,比起其它类型的名称,局部变量名可以有更为宽松的缩写。 +局部变量名以 `lowerCamelCase` 风格编写,比起其它类型的名称,局部变量名可以有更为宽松的缩写。 虽然缩写更宽松,但还是要避免用单字符进行命名,除了临时变量和循环变量。 -即使局部变量是final和不可改变的,也不应该把它示为常量,自然也不能用常量的规则去命名它。 +即使局部变量是 `final` 和不可改变的,也不应该把它示为常量,自然也不能用常量的规则去命名它。 #### 3.8 临时变量 -临时变量通常被取名为`i`、`j`、`k`、`m`和`n`,它们一般用于整型;`c`、`d`、`e`,它们一般用于字符型。 如:`for (int i = 0; i < len ; i++)`。 +临时变量通常被取名为 `i`、`j`、`k`、`m` 和 `n`,它们一般用于整型;`c`、`d`、`e`,它们一般用于字符型。 如:`for (int i = 0; i < len; i++)`。 #### 3.9 类型变量名 类型变量可用以下两种风格之一进行命名: -1. 单个的大写字母,后面可以跟一个数字(如:`E`, `T`, `X`, `T2`)。 -2. 以类命名方式(参考[3.2 类名](#32-类名)),后面加个大写的`T`(如:`RequestT`, `FooBarT`)。 +1. 单个的大写字母,后面可以跟一个数字(如:`E`, `T`, `X`, `T2`)。 +2. 以类命名方式(参考[3.2 类名](#32-类名)),后面加个大写的 T(如:`RequestT`, `FooBarT`)。 + +更多还可参考:**[阿里巴巴 Java 开发手册][阿里巴巴 Java 开发手册]** + + +### 4 代码样式规范 + +#### 4.1 使用标准大括号样式 + +左大括号不单独占一行,与其前面的代码位于同一行: + +```java +class MyClass { + int func() { + if (something) { + // ... + } else if (somethingElse) { + // ... + } else { + // ... + } + } +} +``` + +我们需要在条件语句周围添加大括号。例外情况:如果整个条件语句(条件和主体)适合放在同一行,那么您可以(但不是必须)将其全部放在一行上。例如,我们接受以下样式: + +```java +if (condition) { + body(); +} +``` + +同样也接受以下样式: + +```java +if (condition) body(); +``` + +但不接受以下样式: + +```java +if (condition) + body(); // bad! +``` + + +#### 4.2 编写简短方法 + +在可行的情况下,尽量编写短小精炼的方法。我们了解,有些情况下较长的方法是恰当的,因此对方法的代码长度没有做出硬性限制。如果某个方法的代码超出 40 行,请考虑是否可以在不破坏程序结构的前提下对其拆解。 + + +#### 4.3 类成员的顺序 + +这并没有唯一的正确解决方案,但如果都使用一致的顺序将会提高代码的可读性,推荐使用如下排序: + +1. 常量 +2. 字段 +3. 构造函数 +4. 重写函数和回调 +5. 公有函数 +6. 私有函数 +7. 内部类或接口 + +例如: + +```java +public class MainActivity extends Activity { + + private static final String TAG = MainActivity.class.getSimpleName(); + private String mTitle; + private TextView mTextViewTitle; -更多还可参考~**[阿里巴巴Java开发手册][阿里巴巴Java开发手册]** + @Override + public void onCreate() { + ... + } + public void setTitle(String title) { + mTitle = title; + } -### 4 资源文件规范 + private void setUpView() { + ... + } -#### 4.1 资源布局文件(XML文件(layout布局文件)) + static class AnInnerClass { -全部小写,采用下划线命名法 + } +} +``` + +如果类继承于 Android 组件(例如 `Activity` 或 `Fragment`),那么把重写函数按照他们的生命周期进行排序是一个非常好的习惯,例如,`Activity` 实现了 `onCreate()`、`onDestroy()`、`onPause()`、`onResume()`,它的正确排序如下所示: + +```java +public class MainActivity extends Activity { + //Order matches Activity lifecycle + @Override + public void onCreate() {} + + @Override + public void onResume() {} + + @Override + public void onPause() {} + + @Override + public void onDestroy() {} +} +``` + + +#### 4.4 函数参数的排序 + +在 Android 开发过程中,`Context` 在函数参数中是再常见不过的了,我们最好把 `Context` 作为其第一个参数。 + +正相反,我们把回调接口应该作为其最后一个参数。 -##### 4.1.1 contentView命名 +例如: + +```java +// Context always goes first +public User loadUser(Context context, int userId); -必须以全部单词小写,单词间以下划线分割,使用名词或名词词组。 +// Callbacks always go last +public void loadUserAsync(Context context, int userId, UserCallback callback); +``` -所有Activity或Fragment的contentView必须与其类名对应,对应规则为:将所有字母都转为小写,将类型和功能调换(也就是后缀变前缀)。 -例如:`activity_main.xml` +#### 4.5 字符串常量的命名和值 +Android SDK 中的很多类都用到了键值对函数,比如 `SharedPreferences`、`Bundle`、`Intent`,所以,即便是一个小应用,我们最终也不得不编写大量的字符串常量。 -##### 4.1.2 Dialog命名 +当时用到这些类的时候,我们 **必须** 将它们的键定义为 `static final` 字段,并遵循以下指示作为前缀。 -规则:`dialog_描述.xml` +| 类 | 字段名前缀 | +| ------------------ | ----------- | +| SharedPreferences | `PREF_` | +| Bundle | `BUNDLE_` | +| Fragment Arguments | `ARGUMENT_` | +| Intent Extra | `EXTRA_` | +| Intent Action | `ACTION_` | -例如:`dialog_hint.xml` +说明:虽然 `Fragment.getArguments()` 得到的也是 `Bundle` ,但因为这是 `Bundle` 的常用用法,所以特意为此定义一个不同的前缀。 +例如: + +```java +// 注意:字段的值与名称相同以避免重复问题 +static final String PREF_EMAIL = "PREF_EMAIL"; +static final String BUNDLE_AGE = "BUNDLE_AGE"; +static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID"; + +// 与意图相关的项使用完整的包名作为值的前缀 +static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME"; +static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER"; +``` -##### 4.1.3 PopupWindow命名 -规则:`ppw_描述.xml` +#### 4.6 Activities 和 Fragments 的传参 -例如:`ppw_info.xml` +当 `Activity` 或 `Fragment` 传递数据通过 `Intent` 或 `Bundle` 时,不同值的键须遵循上一条所提及到的。 +当 `Activity` 或 `Fragment` 启动需要传递参数时,那么它需要提供一个 `public static` 的函数来帮助启动或创建它。 -##### 4.1.4 列表项命名 +这方面,AS 已帮你写好了相关的 Live Templates,启动相关 `Activity` 的只需要在其内部输入 `starter` 即可生成它的启动器,如下所示: -规则:`item_描述.xml` +```java +public static void start(Context context, User user) { + Intent starter = new Intent(context, MainActivity.class); + starter.putParcelableExtra(EXTRA_USER, user); + context.startActivity(starter); +} +``` -例如:`item_city.xml` +同理,启动相关 `Fragment` 在其内部输入 `newInstance` 即可,如下所示: +```java +public static MainFragment newInstance(User user) { + Bundle args = new Bundle(); + args.putParcelable(ARGUMENT_USER, user); + MainFragment fragment = new MainFragment(); + fragment.setArguments(args); + return fragment; +} +``` -##### 4.1.5 包含项命名 +> 注意:这些函数需要放在 `onCreate()` 之前的类的顶部;如果我们使用了这种方式,那么 `extras` 和 `arguments` 的键应该是 `private` 的,因为它们不再需要暴露给其他类来使用。 -规则:`模块_(位置)描述.xml` -例如:`activity_main_head.xml`、`activity_main_bottom.xml` +#### 4.7 行长限制 -注意:通用的包含项命名采用:`项目名称缩写_描述.xml` +代码中每一行文本的长度都应该不超过 100 个字符。虽然关于此规则存在很多争论,但最终决定仍是以 100 个字符为上限,如果行长超过了 100(AS 窗口右侧的竖线就是设置的行宽末尾 ),我们通常有两种方法来缩减行长。 -例如:`xxxx_title.xml` +* 提取一个局部变量或方法(最好)。 +* 使用换行符将一行换成多行。 +不过存在以下例外情况: -#### 4.2 资源文件(图片drawable文件夹下) +* 如果备注行包含长度超过 100 个字符的示例命令或文字网址,那么为了便于剪切和粘贴,该行可以超过 100 个字符。 +* 导入语句行可以超出此限制,因为用户很少会看到它们(这也简化了工具编写流程)。 -全部小写,采用下划线命名法,加前缀区分 +##### 4.7.1 换行策略 -命名模式:可加后缀 `_small` 表示小图, `_big` 表示大图,逻辑名称可由多个单词加下划线组成,采用以下规则: +这没有一个准确的解决方案来决定如何换行,通常不同的解决方案都是有效的,但是有一些规则可以应用于常见的情况。 -* `用途_模块名_逻辑名称` -* `用途_模块名_颜色` -* `用途_逻辑名称` -* `用途_颜色` +##### 4.7.1.1 操作符的换行 -说明:用途也指控件类型(具体见附录[UI控件缩写表](#ui控件缩写表)) +除赋值操作符之外,我们把换行符放在操作符之前,例如: + +```java +int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + + theFinalOne; +``` + +赋值操作符的换行我们放在其后,例如: + +```java +int longName = + anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne; +``` + + +##### 4.7.1.2 函数链的换行 + +当同一行中调用多个函数时(比如使用构建器时),对每个函数的调用应该在新的一行中,我们把换行符插入在 `.` 之前。 例如: -| 名称 | 说明 | -| ----------------------- | ----------------------- | -| btn_main_home.png | 按键`用途_模块名_逻辑名称` | -| divider_maket_white.png | 分割线`用途_模块名_颜色` | -| ic_edit.png | 图标`用途_逻辑名称` | -| bg_main.png | 背景`用途_逻辑名称` | -| btn_red.png | 红色按键`用途_颜色` | -| btn_red_big.png | 红色大按键`用途_颜色` | -| ic_head_small.png | 小头像`用途_逻辑名称` | -| bg_input.png | 输入框背景`用途_逻辑名称` | -| divider_white.png | 白色分割线`用途_颜色` | -| bg_main_head | 主模块头部背景图片`用途_模块名_逻辑名称` | -| def_search_cell | 默认搜索界面单元图片`用途_模块名_逻辑名称` | -| ic_more_help | 更多帮助图标`用途_逻辑名称` | -| divider_list_line | 列表分割线`用途_逻辑名称` | -| sel_search_ok | 搜索界面确认选择器`用途_模块名_逻辑名称` | -| shape_music_ring | 音乐界面环形形状`用途_模块名_逻辑名称` | - -如果有多种形态,如按钮选择器:`sel_btn_xx.xml` - -| 名称 | 说明 | -| -------------------- | ---------------------------- | -| sel_btn_xx | 按钮图片使用`btn_整体效果`(selector) | -| btn_xx_normal | 按钮图片使用`btn_正常情况效果` | -| btn_xx_pressed | 按钮图片使用`btn_点击时候效果` | -| btn_xx_focused | `state_focused`聚焦效果 | -| btn_xx_disabled | `state_enabled` (false)不可用效果 | -| btn_xx_checked | `state_checked`选中效果 | -| btn_xx_selected | `state_selected`选中效果 | -| btn_xx_hovered | `state_hovered`悬停效果 | -| btn_xx_checkable | `state_checkable`可选效果 | -| btn_xx_activated | `state_activated`激活的 | -| btn_xx_windowfocused | `state_window_focused` | - -> 注意:使用AndroidStudio的插件`SelectorChapek`可以快速生成selector,前提是命名要规范。 - - -#### 4.3 动画文件(anim文件夹下) - -全部小写,采用下划线命名法,加前缀区分。 - -具体动画采用以下规则:`模块名_逻辑名称`。 +```java +Picasso.with(context).load("https://blankj.com/images/avatar.jpg").into(ivAvatar); +``` + +我们应该使用如下规则: + +```java +Picasso.with(context) + .load("https://blankj.com/images/avatar.jpg") + .into(ivAvatar); +``` + + +##### 4.7.1.3 多参数的换行 + +当一个方法有很多参数或者参数很长的时候,我们应该在每个 `,` 后面进行换行。 + +比如: + +```java +loadPicture(context, "https://blankj.com/images/avatar.jpg", ivAvatar, "Avatar of the user", clickListener); +``` + +我们应该使用如下规则: + +```java +loadPicture(context, + "https://blankj.com/images/avatar.jpg", + ivAvatar, + "Avatar of the user", + clickListener); +``` + + +##### 4.7.1.4 RxJava 链式的换行 + +RxJava 的每个操作符都需要换新行,并且把换行符插入在 `.` 之前。 + +例如: + +```java +public Observable syncLocations() { + return mDatabaseHelper.getAllLocations() + .concatMap(new Func1>() { + @Override + public Observable call(Location location) { + return mRetrofitService.getLocation(location.id); + } + }) + .retry(new Func2() { + @Override + public Boolean call(Integer numRetries, Throwable throwable) { + return throwable instanceof RetrofitError; + } + }); +} +``` + + +### 5 资源文件规范 + +资源文件命名为全部小写,采用下划线命名法。 + +如果是组件化开发,我们可以在组件和公共模块间创建一个 ui 模块来专门存放资源文件,然后让每个组件都依赖 ui 模块。这样做的好处是如果老项目要实现组件化的话,只需把资源文件都放入 ui 模块即可,如果想对资源文件进行分包,可以参考我这篇文章:**[Android Studio 下对资源进行分包][Android Studio 下对资源进行分包]**;还避免了多个模块间资源不能复用的问题。 + +如果是三方库开发,其使用到的资源文件及相关的 `name` 都应该使用库名作为前缀,这样做可以避免三方库资源和实际应用资源重名的冲突。 + +#### 5.1 动画资源文件(anim/ 和 animator/) + +安卓主要包含属性动画和视图动画,其视图动画包括补间动画和逐帧动画。属性动画文件需要放在 `res/animator/` 目录下,视图动画文件需放在 `res/anim/` 目录下。 + +命名规则:`{模块名_}逻辑名称`。 + +说明:`{}` 中的内容为可选,`逻辑名称` 可由多个单词加下划线组成。 例如:`refresh_progress.xml`、`market_cart_add.xml`、`market_cart_remove.xml`。 -普通的tween动画采用如下表格中的命名方式:`动画类型_方向` +如果是普通的补间动画或者属性动画,可采用:`动画类型_方向` 的命名方式。 + +例如: + +| 名称 | 说明 | +| ------------------- | ------- | +| `fade_in` | 淡入 | +| `fade_out` | 淡出 | +| `push_down_in` | 从下方推入 | +| `push_down_out` | 从下方推出 | +| `push_left` | 推向左方 | +| `slide_in_from_top` | 从头部滑动进入 | +| `zoom_enter` | 变形进入 | +| `slide_in` | 滑动进入 | +| `shrink_to_middle` | 中间缩小 | -| 名称 | 说明 | -| ----------------- | ------- | -| fade_in | 淡入 | -| fade_out | 淡出 | -| push_down_in | 从下方推入 | -| push_down_out | 从下方推出 | -| push_left | 推向左方 | -| slide_in_from_top | 从头部滑动进入 | -| zoom_enter | 变形进入 | -| slide_in | 滑动进入 | -| shrink_to_middle | 中间缩小 | +#### 5.2 颜色资源文件(color/) -#### 4.4 values中name命名 +专门存放颜色相关的资源文件。 -##### 4.4.1 colors.xml +命名规则:`类型{_模块名}_逻辑名称`。 -`colors.xml`的`name`命名使用下划线命名法,在你的`colors.xml`文件中应该只是映射颜色的名称一个ARGB值,而没有其它的。不要使用它为不同的按钮来定义ARGB值。 +说明:`{}` 中的内容为可选。 -**不要这样做** +例如:`sel_btn_font.xml`。 + +颜色资源也可以放于 `res/drawable/` 目录,引用时则用 `@drawable` 来引用,但不推荐这么做,最好还是把两者分开。 + + +#### 5.3 图片资源文件(drawable/ 和 mipmap/) + +`res/drawable/` 目录下放的是位图文件(.png、.9.png、.jpg、.gif)或编译为可绘制对象资源子类型的 XML 文件,而 `res/mipmap/` 目录下放的是不同密度的启动图标,所以 `res/mipmap/` 只用于存放启动图标,其余图片资源文件都应该放到 `res/drawable/` 目录下。 + +命名规则:`类型{_模块名}_逻辑名称`、`类型{_模块名}_颜色`。 + +说明:`{}` 中的内容为可选;`类型` 可以是[可绘制对象资源类型](可绘制对象资源类型),也可以是控件类型(具体见附录[UI 控件缩写表](#ui-控件缩写表));最后可加后缀 `_small` 表示小图,`_big` 表示大图。 + +例如: + +| 名称 | 说明 | +| ------------------------- | ------------------------ | +| `btn_main_about.png` | 主页关于按键 `类型_模块名_逻辑名称` | +| `btn_back.png` | 返回按键 `类型_逻辑名称` | +| `divider_maket_white.png` | 商城白色分割线 `类型_模块名_颜色` | +| `ic_edit.png` | 编辑图标 `类型_逻辑名称` | +| `bg_main.png` | 主页背景 `类型_逻辑名称` | +| `btn_red.png` | 红色按键 `类型_颜色` | +| `btn_red_big.png` | 红色大按键 `类型_颜色` | +| `ic_head_small.png` | 小头像图标 `类型_逻辑名称` | +| `bg_input.png` | 输入框背景 `类型_逻辑名称` | +| `divider_white.png` | 白色分割线 `类型_颜色` | +| `bg_main_head.png` | 主页头部背景 `类型_模块名_逻辑名称` | +| `def_search_cell.png` | 搜索页面默认单元图片 `类型_模块名_逻辑名称` | +| `ic_more_help.png` | 更多帮助图标 `类型_逻辑名称` | +| `divider_list_line.png` | 列表分割线 `类型_逻辑名称` | +| `sel_search_ok.xml` | 搜索界面确认选择器 `类型_模块名_逻辑名称` | +| `shape_music_ring.xml` | 音乐界面环形形状 `类型_模块名_逻辑名称` | + +如果有多种形态,如按钮选择器:`sel_btn_xx.xml`,采用如下命名: + +| 名称 | 说明 | +| ----------------------- | ----------------------------- | +| `sel_btn_xx` | 作用在 `btn_xx` 上的 `selector` | +| `btn_xx_normal` | 默认状态效果 | +| `btn_xx_pressed` | `state_pressed` 点击效果 | +| `btn_xx_focused` | `state_focused` 聚焦效果 | +| `btn_xx_disabled` | `state_enabled` 不可用效果 | +| `btn_xx_checked` | `state_checked` 选中效果 | +| `btn_xx_selected` | `state_selected` 选中效果 | +| `btn_xx_hovered` | `state_hovered` 悬停效果 | +| `btn_xx_checkable` | `state_checkable` 可选效果 | +| `btn_xx_activated` | `state_activated` 激活效果 | +| `btn_xx_window_focused` | `state_window_focused` 窗口聚焦效果 | + +> 注意:使用 Android Studio 的插件 SelectorChapek 可以快速生成 selector,前提是命名要规范。 + + +#### 5.4 布局资源文件(layout/) + +命名规则:`类型_模块名`、`类型{_模块名}_逻辑名称`。 + +说明:`{}` 中的内容为可选。 + +例如: + +| 名称 | 说明 | +| --------------------------- | --------------------------- | +| `activity_main.xml` | 主窗体 `类型_模块名` | +| `activity_main_head.xml` | 主窗体头部 `类型_模块名_逻辑名称` | +| `fragment_music.xml` | 音乐片段 `类型_模块名` | +| `fragment_music_player.xml` | 音乐片段的播放器 `类型_模块名_逻辑名称` | +| `dialog_loading.xml` | 加载对话框 `类型_逻辑名称` | +| `ppw_info.xml` | 信息弹窗(PopupWindow) `类型_逻辑名称` | +| `item_main_song.xml` | 主页歌曲列表项 `类型_模块名_逻辑名称` | + + +#### 5.5 菜单资源文件(menu/) + +菜单相关的资源文件应放在该目录下。 + +命名规则:`{模块名_}逻辑名称` + +说明:`{}` 中的内容为可选。 + +例如:`main_drawer.xml`、`navigation.xml`。 + + +#### 5.6 values 资源文件(values/) + +`values/` 资源文件下的文件都以 `s` 结尾,如 `attrs.xml`、`colors.xml`、`dimens.xml`,起作用的不是文件名称,而是 `` 标签下的各种标签,比如 ` ``` -应用到`TextView`中: +应用到 `TextView` 中: ``` ``` -你或许需要为按钮控件做同样的事情,不要停止在那里。将一组相关的和重复`android:****`的属性放到一个通用的`style`中。 +或许你需要为按钮控件做同样的事情,不要停止在那里,将一组相关的和重复 `android:xxxx` 的属性放到一个通用的 `