├── images
├── pay.png
└── logo.png
├── 2015.9
├── ui
│ ├── 1.png
│ ├── 10.png
│ ├── 11.png
│ ├── 2.png
│ ├── 3.png
│ ├── 4.png
│ ├── 5.png
│ ├── 6.png
│ ├── 7.png
│ ├── 8.png
│ ├── 9.png
│ ├── avatar.png
│ ├── tablayout.gif
│ ├── viewpager.gif
│ └── ui.md
└── reflect
│ ├── avatar.jpg
│ ├── README - chinese.md
│ └── reflect.md
├── README.md
└── LICENSE
/images/pay.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/images/pay.png
--------------------------------------------------------------------------------
/2015.9/ui/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/1.png
--------------------------------------------------------------------------------
/2015.9/ui/10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/10.png
--------------------------------------------------------------------------------
/2015.9/ui/11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/11.png
--------------------------------------------------------------------------------
/2015.9/ui/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/2.png
--------------------------------------------------------------------------------
/2015.9/ui/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/3.png
--------------------------------------------------------------------------------
/2015.9/ui/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/4.png
--------------------------------------------------------------------------------
/2015.9/ui/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/5.png
--------------------------------------------------------------------------------
/2015.9/ui/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/6.png
--------------------------------------------------------------------------------
/2015.9/ui/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/7.png
--------------------------------------------------------------------------------
/2015.9/ui/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/8.png
--------------------------------------------------------------------------------
/2015.9/ui/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/9.png
--------------------------------------------------------------------------------
/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/images/logo.png
--------------------------------------------------------------------------------
/2015.9/ui/avatar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/avatar.png
--------------------------------------------------------------------------------
/2015.9/ui/tablayout.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/tablayout.gif
--------------------------------------------------------------------------------
/2015.9/ui/viewpager.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/ui/viewpager.gif
--------------------------------------------------------------------------------
/2015.9/reflect/avatar.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kaleai/Android-Best-Practices/HEAD/2015.9/reflect/avatar.jpg
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android-Best-Practices
2 |
3 | [](https://gitter.im/tianzhijiexian/Android-Best-Practices?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
4 | [](http://issuestats.com/github/tianzhijiexian/Android-Best-Practices)
5 |
6 |
7 |
8 | 如果你也想参与或者是对文中内容有所补充,可以通过评论或邮件的方式进行告知,我很希望可以和大家一同完善本项目。
9 |
10 | 起笔时间2015年8月30日(晚)
11 |
12 | ### 目录
13 |
14 | 年 | 月 | 文章 |
15 | --- | --- | --- |
16 | 2015 | 08 | [Log最佳实践](https://gold.xitu.io/post/5848ba24b123db006601febf) |
17 | | 09 | [Java反射最佳实践](https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/reflect/reflect.md) |
18 | | | [UI实时预览最佳实践](https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/ui/ui.md) |
19 | | 10 | [Adapter最佳实践](https://gold.xitu.io/post/589688d0b123db16a39cc46b) |
20 | 2016 | 04 | [Selector最佳实践](https://www.zybuluo.com/shark0017/note/333443) |
21 | | 05 | [开发第三方库最佳实践](http://www.jianshu.com/p/0aacd419cb7e) |
22 | | 06 | [集成第三方推送最佳实践](http://www.jianshu.com/p/d650d02a1c7a) |
23 | | 07 | [打包提速最佳实践](http://gold.xitu.io/post/5831301a0ce463006c044c77) |
24 | | 08 | [DataBinding最佳实践](http://www.jianshu.com/p/1fcda521fcda) |
25 | | 09 | [App瘦身最佳实践](http://www.jianshu.com/p/8f14679809b3) |
26 | | 10 | [Gradle配置最佳实践](http://gold.xitu.io/post/582d606767f3560063320b21) |
27 | | 11 | [第三方登录/分享最佳实践](https://juejin.im/post/58c21aa944d9040068e71e2c) |
28 | 2017 | 07 | [Dialog最佳实践](https://juejin.im/post/595afcac6fb9a06b9c7411e2) |
29 |
30 | ### 初衷
31 | 起笔写这个项目的原因很简单,面对世面上众多的第三方库,我们很难在短时间内知道什么是最好的。开源平台虽百家争鸣,但落实到开发者的项目中也终究是成王败寇的结局。我希望带给大家一些市面上最好的开源库或解决方案,让大家能快速找到质量最好的第三方库。
32 |
33 | 我更希望的是,一个初创公司的开发者能在看完这系列文章后,善用轮子,这样能在保证项目开发速度的前提下,还能有点代码质量(并非贬义,经历过的人懂)。当然了,我一个人的力量和知识是有限的,所以我把它放在github上面。希望大家能参与进来,推荐优质的第三方库或者解决方案。
34 |
35 | ### 说明
36 | 1. 本文主要是文字内容,所以我会不定期的更新和修改之前的文章内容。所以推荐大家watch下本项目,这样有更新了可以及时提醒。
37 | 2. 关于文章的放置地点,我选择了第三方的平台,没有放在github上。因为git的东西每次都要产生一个commit,不够随意。
38 | 3. 老的文章会随着推荐的库的更新而更新,如果老的文章更新了,我“有可能”会在微博上发布信息。
39 |
40 | ### 尾记
41 | 学生时期自己有着无穷的自信,毕业后发现必须要用实力来面对现实。现在我虽然不能像以前那样穷尽全力去帮助别人,也不能改变世界,但我希望自己仍能够不断地坚持一些事情,即使是一点点微小的工作。 ———— 在现实中苟延残喘的理想主义者
42 |
43 | ### 推荐文章
44 |
45 | 类别 | 文章
46 | --- | ---
47 | debug | [你所不知道的Android Studio调试技巧](http://www.jianshu.com/p/011eb88f4e0d)
48 | keymap | [Android Studio 小技巧/快捷键 合集](http://jaeger.itscoder.com/android/2016/02/14/android-studio-tips.html)
49 |
50 |
51 | ### Developer
52 |
53 | 
54 |
55 | Jack Tony:
56 |
57 | ### License
58 |
59 | Copyright 2015-2019 Jack Tony
60 |
61 | Licensed under the Apache License, Version 2.0 (the "License");
62 | you may not use this file except in compliance with the License.
63 | You may obtain a copy of the License at
64 |
65 | http://www.apache.org/licenses/LICENSE-2.0
66 |
67 | Unless required by applicable law or agreed to in writing, software
68 | distributed under the License is distributed on an "AS IS" BASIS,
69 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
70 | See the License for the specific language governing permissions and
71 | limitations under the License.
72 |
73 | ---
74 | **捐助此项目**
75 |
76 | 
77 |
--------------------------------------------------------------------------------
/2015.9/reflect/README - chinese.md:
--------------------------------------------------------------------------------
1 | ### 概要
2 |
3 | jOOR是基于java反射api的一个简单包装类,简单却十分实用。
4 |
5 | jOOR这个名字是从jOOQ中得到的灵感,jOOQ是一个很棒的SQL的API。
6 |
7 | ### 基于的库
8 |
9 | 完全不用!
10 |
11 | ### 一个简单的示例
12 |
13 | ```JAVA
14 | // All examples assume the following static import:
15 | import static org.joor.Reflect.*;
16 |
17 | String world = on("java.lang.String") // on后面放入类的全名,这里是String类
18 | .create("Hello World") // 将字符串“Hello World”,传入构造方法中
19 | .call("substring", 6) // 执行subString这个方法,并且传入6作为参数
20 | .call("toString") // 执行toString方法
21 | .get(); // 得到包装好的类,这里是一个String对象
22 | ```
23 |
24 |
25 | ### 抽象代理
26 |
27 | jOOR也可以方便的使用java.lang.reflect.Proxy的API
28 | ```java
29 | public interface StringProxy {
30 | String substring(int beginIndex);
31 | }
32 |
33 | String substring = on("java.lang.String")
34 | .create("Hello World")
35 | .as(StringProxy.class) // 为包装类建立一个代理
36 | .substring(6); // 访问代理方法
37 | ```
38 |
39 |
40 | ### 和java.lang.reflect的对比
41 |
42 | 使用jOOR的代码:
43 |
44 | ```java
45 | Employee[] employees = on(department).call("getEmployees").get();
46 |
47 | for (Employee employee : employees) {
48 | Street street = on(employee).call("getAddress").call("getStreet").get();
49 | System.out.println(street);
50 | }
51 | ```
52 |
53 | 用传统的反射方式写的代码:
54 |
55 | ```java
56 | try {
57 | Method m1 = department.getClass().getMethod("getEmployees");
58 | Employee employees = (Employee[]) m1.invoke(department);
59 |
60 | for (Employee employee : employees) {
61 | Method m2 = employee.getClass().getMethod("getAddress");
62 | Address address = (Address) m2.invoke(employee);
63 |
64 | Method m3 = address.getClass().getMethod("getStreet");
65 | Street street = (Street) m3.invoke(address);
66 |
67 | System.out.println(street);
68 | }
69 | }
70 |
71 | // There are many checked exceptions that you are likely to ignore anyway
72 | catch (Exception ignore) {
73 |
74 | // ... or maybe just wrap in your preferred runtime exception:
75 | throw new RuntimeException(e);
76 | }
77 | ```
78 | ### 更多示例
79 | 建立一个测试类:
80 | ```JAVA
81 | package kale.androidframework;
82 |
83 | public class Kale {
84 |
85 | private String name;
86 |
87 | private String className;
88 |
89 | Kale() {
90 |
91 | }
92 |
93 | Kale(String clsName) {
94 | this.className = clsName;
95 | }
96 |
97 | public void setName(String name) {
98 | this.name = name;
99 | }
100 |
101 | private String getName() {
102 | return name;
103 | }
104 |
105 | public String getClassName() {
106 | return className;
107 | }
108 |
109 | public static void method() {
110 |
111 | }
112 | }
113 | ```
114 | 这个类中有有参构造方法和无参构造方法,还有get和set方法。这里的类变量都是private的,有一个get方法也是private的。我们现在要尝试利用jOOR来访问变量和方法:
115 | ```JAVA
116 | String name = null;
117 | Kale kale;
118 | // 【创建类】
119 | kale = Reflect.on(Kale.class).create().get(); // 无参数
120 | kale = Reflect.on(Kale.class).create("kale class name").get();// 有参数
121 | System.err.println("------------------> class name = " + kale.getClassName());
122 |
123 | // 【调用方法】
124 | Reflect.on(kale).call("setName","调用setName");// 多参数
125 | System.err.println("调用方法:name = " + Reflect.on(kale).call("getName"));// 无参数
126 |
127 | // 【得到变量】
128 | name = Reflect.on(kale).field("name").get();// 复杂
129 | name = Reflect.on(kale).get("name");// 简单
130 | System.err.println("得到变量值: name = " + name);
131 |
132 | // 【设置变量的值】
133 | Reflect.on(kale).set("className", "hello");
134 | System.err.println("设置变量的值: name = " + kale.getClassName());
135 | System.err.println("设置变量的值: name = " + Reflect.on(kale).set("className", "hello2").get("className"));
136 | ```
137 |
138 | ### 相似的工程
139 |
140 | Everyday Java reflection with a fluent interface:
141 |
142 | * http://docs.codehaus.org/display/FEST/Reflection+Module
143 | * http://projetos.vidageek.net/mirror/mirror/
144 |
145 | Reflection modelled as XPath (quite interesting!)
146 |
147 | * http://commons.apache.org/jxpath/users-guide.html
148 |
149 |
150 |
151 |
152 |
153 |
--------------------------------------------------------------------------------
/2015.9/reflect/reflect.md:
--------------------------------------------------------------------------------
1 | # Java反射最佳实践
2 |
3 | **概要:最简单优雅的使用反射。**
4 | 本文的例子都可以在示例代码中看到并下载,如果喜欢请star,如果觉得有纰漏请提交issue,如果你有更好的点子可以提交pull request。本文的示例代码主要是基于[jOOR][1]行编写的,如果想了解更多请查看[这里][2]的测试代码。
5 | 固定连接:[https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/reflect/reflect.md][3]
6 |
7 | ### 一、需求
8 | 今天一个“懒”程序员突然跑过来说:“反射好麻烦,我要提点需求。”
9 | 听到这句话后我就知道,今天一定不好过了,奇葩需求又来了。
10 |
11 | 我们之前写反射都是要这么写:
12 | ```java
13 | public static T create(HttpRequest httpRequest) {
14 | Object httpRequestEntity = null;
15 | try {
16 | Class httpRequestEntityCls = (Class) Class.forName(HttpProcessor.PACKAGE_NAME + "." + HttpProcessor.CLASS_NAME);
17 | Constructor con = httpRequestEntityCls.getConstructor(HttpRequest.class);
18 | httpRequestEntity = con.newInstance(httpRequest);
19 | } catch (ClassNotFoundException e) {
20 | e.printStackTrace();
21 | } catch (InstantiationException e) {
22 | e.printStackTrace();
23 | } catch (IllegalAccessException e) {
24 | e.printStackTrace();
25 | } catch (NoSuchMethodException e) {
26 | e.printStackTrace();
27 | } catch (InvocationTargetException e) {
28 | e.printStackTrace();
29 | }
30 | return (T) httpRequestEntity;
31 | }
32 | ```
33 | 因为反射在开发中很少用(做普通的业务开发的话),仅仅在自己写一些框架和注解框架时会用到,所以对api总是不熟悉。每次用到api都要去网上查,查了后又得自己实验下,很不爽。更差劲的是这样写法可读性十分低下。我不希望这样写反射,我希望反射能像
34 | ```JAVA
35 | String str = new String();
36 | ```
37 | 这样简单,**一行代码搞定!**。
38 | 此外,有很多人都说反射影响性能,在开发的时候要避免用反射。那么什么时候该用反射,什么时候不用反射呢?用什么方式来避免反射呢?如果不明白**什么时候用反射**,就很难将反射活学活用了。
39 |
40 |
41 | ### 二、分析
42 | 当我们接到上面需求后,我长舒一口气,因为这回的需求还比较简单。
43 | 我相信有人会说:“反射就那几个api,一直没变过,你就不会自己去查啊,觉得麻烦就别写代码啊,不知道反射的内部细节你怎么去提高呢?”
44 | 其实不然,重复写麻烦的代码和提高自己的代码能力是完全无关的,我实在不知道我们写了成千上万行的`findViewById`后除了知道类要和xml文件绑定外,还学到了什么。
45 | 那么这回我们继续来挑战传统思维和模板式代码,来看看新一代的反射代码应该怎么写,如何用一行代码来反射出类。
46 | 在做之前,来看看我们一般用反射来干嘛?
47 |
48 | 1. 反射构建出无法直接访问的类
49 | 2. set或get到无法访问的类变量
50 | 3. 调用不可访问的方法
51 |
52 |
53 | ### 三、解决方案
54 | #### 3.1 一行代码写反射
55 | 作为一个Android程序员,索性就拿`TextView`这个类开刀吧。首先定义一个类变量:
56 | ```JAVA
57 | TextView mTv;
58 | ```
59 | **通过反射得到实例:**
60 | ```JAVA
61 | // 有参数,建立类
62 | mTv = Reflect.on(TextView.class).create(this).get();
63 |
64 | // 通过类全名得到类
65 | String word = Reflect.on("java.lang.String").create("Reflect TextView").get();
66 |
67 | // 无参数,建立类
68 | Fragment fragment = Reflect.on(Fragment.class).create().get();
69 | ```
70 | **通过反射调用方法:**
71 | ```JAVA
72 | // 调用无参数方法
73 | L.d("call getText() : " + Reflect.on(mTv).call("getText").toString());
74 |
75 | // 调用有参数方法
76 | Reflect.on(mTv).call("setTextColor", 0xffff0000);
77 | ```
78 |
79 | **通过反射get、set类变量**
80 | TextView中有个mText变量,来看看我们怎么接近它。
81 | ```JAVA
82 | // 设置参数
83 | Reflect.on(mTv).set("mText", "---------- new Reflect TextView ----------");
84 |
85 | // 获得参数
86 | L.d("setgetParam is " + Reflect.on(mTv).get("mText"));
87 | ```
88 |
89 | #### 3.2 什么时候该用反射,什么时候不用反射
90 | 又到了这样权衡利弊的时候了,首先我们明确,在日常开发中尽量不要用反射,除非遇到了必须要通过反射才能调用的方法。比如我在做一个下拉通知中心功能的时候就遇到了这样的情况。系统没有提供api,所以我们只能通过反射进行调用,所以我自己写了这样一段代码:
91 | ```xml
92 |
93 | ```
94 | ```JAVA
95 | private static void doInStatusBar(Context mContext, String methodName) {
96 | try {
97 | Object service = mContext.getSystemService("statusbar");
98 | Method expand = service.getClass().getMethod(methodName);
99 | expand.invoke(service);
100 | } catch (Exception e) {
101 | e.printStackTrace();
102 | }
103 | }
104 |
105 | /**
106 | * 显示消息中心
107 | */
108 | public static void openStatusBar(Context mContext) {
109 | // 判断系统版本号
110 | String methodName = (VERSION.SDK_INT <= 16) ? "expand" : "expandNotificationsPanel";
111 | doInStatusBar(mContext, methodName);
112 | }
113 |
114 | /**
115 | * 关闭消息中心
116 | */
117 | public static void closeStatusBar(Context mContext) {
118 | // 判断系统版本号
119 | String methodName = (VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels";
120 | doInStatusBar(mContext, methodName);
121 | }
122 | ```
123 | 先来看看利用jOOR写的`doInStatusBar`方法会简洁到什么程度:
124 | ```JAVA
125 | private static void doInStatusBar(Context mContext, String methodName) {
126 | Object service = mContext.getSystemService("statusbar");
127 | Reflect.on(service).call(methodName);
128 | }
129 | ```
130 | 哇,就一行代码啊,很爽吧~
131 | 爽完了,我们就来看看反射问题吧。因为不是系统给出的api,所以谷歌在不同的版本上用了不同的方法名来做处理,用反射的话我们就必须进行版本的判断,这是需要注意的,此外反射在性能方面确实不好,这里需要谨慎。
132 | 我的建议:
133 | 如果一个类中有很多地方都是private的,而你的需求都需要依赖这些方法或者变量,那么比起用反射,推荐把这个类复制出来,变成自己的类,像是toolbar这样的类就可以进行这样的操作。
134 | 在自己写框架的时候,我们肯定会用到反射,很简单的例子就是事件总线和注解框架,翔哥就说过一句话:**无反射,无框架**。也正因为是自己写的框架,所以通过反射调用的方法名和参数一般不会变,更何况做运行时注解框架的话,反射肯定会出现。在这种情况下千万不要害怕反射,索性放心大胆的做。因为它会让你完成很多不可能完成的任务。
135 | 总结下来就是:
136 | 实际进行日常开发的时候尽量少用反射,可以通过复制原始类的形式来避免反射。在写框架时,不避讳反射,在关键时利用反射来助自己一臂之力。
137 |
138 |
139 | ### 四、后记
140 | 我们终于完成了用一行代码写反射,避免了很多无意义的模板式代码。需要再次说明的是,本文是依据[jOOR][4] 进行编写的,[这里][7]有原项目readme的中文翻译。
141 | jOOR是我无意中遇到的开源库,第一次见到它时我就知道这个是我想要的,因为那时候我被反射搞的很乱,而它简洁的编码方式给我带来了新的思考,大大提高了代码可读性。顺便一说,作者人比较好(就是死活不愿意让我放入中文的readme),技术也很不错。该项目有很详细的测试用例,并且还给出了几个类似的反射调用封装库。可见作者在写库时做了大量的调研和测试工作,让我们可以放心的运用该库*(其实就两个类)*。
142 | 本文希望带给大家一个反射的新思路,给出一个最简单实用的反射写法,希望能被大家迅速运用到实践中去。更加重要的是,通过对jOOR的分析,让我知道了写库前应该调研类似的库,而不是完全的创造新轮子,调研和测试是代码稳定性的重要保障。
143 |
144 | ### 参考自
145 | [http://www.cnblogs.com/tianzhijiexian/p/3906774.html][5]
146 | [https://github.com/tianzhijiexian/HttpAnnotation/blob/master/lib/src/main/java/kale/net/http/util/HttpReqAdapter.java][6]
147 |
148 | ### 作者
149 | 
150 |
151 | developer_kale@qq.com
152 | @天之界线2010
153 |
154 |
155 | [1]: https://github.com/jOOQ/jOOR
156 | [2]: https://github.com/jOOQ/jOOR/tree/master/jOOR/src/test/java/org/joor/test
157 | [3]: https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/reflect/reflect.md
158 | [4]: https://github.com/jOOQ/jOOR
159 | [5]: http://www.cnblogs.com/tianzhijiexian/p/3906774.html
160 | [6]: https://github.com/tianzhijiexian/HttpAnnotation/blob/master/lib/src/main/java/kale/net/http/util/HttpReqAdapter.java
161 | [7]: https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/reflect/README%20-%20chinese.md
162 |
--------------------------------------------------------------------------------
/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 |
203 |
--------------------------------------------------------------------------------
/2015.9/ui/ui.md:
--------------------------------------------------------------------------------
1 | # UI实时预览最佳实践
2 |
3 | **概要:Android中实时预览UI和编写UI的各种技巧。**
4 | 本文的例子都可以在结尾处的示例代码中看到并下载。如果喜欢请star,如果觉得有纰漏请提交issue,如果你有更好的点子可以提交pull request。
5 | 本文的代码主要是基于作者的实际经验编写的,如果你有其他的技巧和方法也可以参与进来一起完善此文。
6 | 文章固定连接:[https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/ui/ui.md](https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.9/ui/ui.md)
7 |
8 | ### 一、啰嗦
9 | 之前有读者反馈说,你搞这个所谓的最佳实践,每篇文章最后就给了一个库,感觉不是很高大上。其实,我在写这个系列之初就有想过这个问题。我的目的是:给出最实用的库来帮助我们开发,并且尽可能地说明这个库是如何编写的,希望让初创公司的程序员少写点给后人留坑的代码(**想必大家对此深有体会**)。
10 | 我之前给出的库都是很简单基础的,基本是一看就懂(*但足够精妙*),如果以后的文章涉及到了复杂的库,我会专门附加一篇库的讲解文。
11 | 如果一个库的原理你知道,此外这个库很容易扩展和维护,而且它还用到了很多最佳实践的经验,你为什么不去试试呢?程序的意义在于把前人的优秀思维和丰富经验记录下来,让使用者可以轻易地站在巨人的肩膀上。它的意义甚至堪比于将祖先的智慧通过DNA遗传给我们,它是一种颠覆性的存在。如果我仅仅是分享自己在实践中获得的很多经验,这就不是程序,而是教育!
12 | 令人遗憾的是,我只能将很多有章可循的东西包装为库,而调试UI这种杂乱无章的技巧只能通过文章来记录,故产生了此文。
13 |
14 | ### 二、需求
15 | 有很多初学者都听到前辈们说Android Studio(下文简称为as)的布局实时预览很强大,但是当我们真正使用as后就会发现很多界面在预览时是这样的:
16 | 
17 | 或者这样的:
18 | 
19 | 甚至是这样的:
20 | 
21 | 这时候谁再和我讲as可以让你实时地编写UI,我就要和谁拼命了。(┬_┬)
22 | 其实这个不是as的错,而是开发者(包括google的开发人员)的错。因为很多开发者不注重实时的ui显示,一切都是以真机运行的结果做评判标准,从而产生了很多无法预览,但能运行的界面。在很多项目中,一个原本可以一秒内看到的效果,最终需要漫长的过程(编译->运行->安装->显示)才能被我们看到。我不得不说这是反人类的,大大降低了Android程序员的开发效率,破坏了开发的心情(**我是很注重开发心情的**),让as强大的预览功能变得形同虚设。那么,既然官方不作为,只有我们自己来!下面就来说说如何让自己的UI可实时调试的方案和技巧。
23 |
24 | ### 三、原则与技巧
25 | **3.0 指导性原则**
26 | 将一次性的属性放入xml中,将需要根据程序运行产生变化的属性放入java代码中。
27 | 得益于布局文件的可预览性(即使某个控件不可预览,我们也应该让其支持预览,下文会给出方案),我们可以大胆的编写xml布局,而不用担心后期维护难以定位的问题。仅将动态变化的东西放入java代码中,就可以让可变和不可变的代码进行分离,从而在本质上趋于设计模式原则,在以后的编写过程中你将会发现代码自动产生了很多优化的空间,可读性也增强了很多。
28 |
29 | **3.1 少用merge标签**
30 | 很多文章都说为了避免层级加深请用merge标签,但是我这里却说少用它。原因有两点:
31 | 1. merge标签会让布局中各个元素的关系错乱,无法准确的显示ui位置(预览时)。
32 | 2. 在merge标签中会失去as自动的代码提示功能,让编写变得困难。
33 | 这两点对于UI的实时预览是极为致命的,所以推荐先用linearLayout等viewgroup做根布局,等编写完毕了后再用merge来代替。我倒不是说merge标签不好,merge标签的设计思路是很棒的,我只是想指出其问题。可惜的是,这两个问题目前没什么其他的好的解决方案了,只能等官方改进IDE和增加tools的功能吧。
34 | **【吐槽】**
35 | 一个很棒的merge标签被这两个因素弄的很别扭,真是令人伤心,和它同病相怜的还有tools这个命名空间。
36 |
37 | **3.2 多用tools的属性**
38 | `xmlns:tools="http://schemas.android.com/tools"`是一个很重要也是很好用的命名空间,它拥有`android:`中所有的属性,但它标识的属性仅仅在预览中有效,不会影响真正的运行结果。
39 | 举个例子:
40 | ```xml
41 |
46 | ```
47 | 这是我们之前的一个写法,把textView的text属性用`android:`来标识。如果我们希望这个textview的文字在代码中实时控制,默认是没文字怎么办?这就需要`tools`的帮助了。
48 | ```xml
49 |
54 | ```
55 | 把第一行的`android`替换为`tools`这样既可以能在预览中看到效果,又不会影响代码实际运行的结果。因为在实际运行的时候被`tools`标记的属性是会被忽略的。你完全可以理解为它是一个测试环境,这个测试环境和真实环境是完全独立的,不会有任何影响。
56 |
57 | **【吐槽】**
58 | tools标签不支持代码提示,而且自己的属性也不能提示,全是靠自己记忆,或者先用android来代替,然后替换android为tools。这么长时间以来,google貌似一直没管它,这也印证了google程序员也是不怎么爱实时预览布局的人。
59 |
60 | **3.3 用tools来让listview支持实时预览**
61 | 在之前的代码中,我们总是这样写listview,然后脑补一下item放入的样子。
62 | ```XML
63 |
64 |
68 | ```
69 | 
70 | 现在我们可以利用`tools`来预览item被放入的样子了,就像这样:
71 | ```XML
72 |
73 |
80 | ```
81 | 
82 | 是不是好了很多呢。
83 | 利用tools的这两个属性可以让我们不用盲写UI了,也可以给设计一个很直观的展示。
84 |
85 | **3.4 利用drawableXXX属性来做有图文的控件**
86 | textview和其子类都拥有`drawableLeft`、`drawableRight`等属性,通过这些属性可以让我们很方便的做出有图文控件。`drawablePadding`可以设置图文之间的间距,但可惜没有drawableLeftPadding之类的属性。
87 | 比如我们要做一个两边有icon,文字居中的控件:
88 | 
89 | ```XML
90 |
91 |
103 | ```
104 | 这时如果想调整文字位置,只需要修改`gravity`的值即可。
105 | 
106 | 我们常见的这种(文字+箭头)的控件就可以按照如下方式进行制作:
107 | ```XML
108 |
109 |
121 | ```
122 |
123 | **3.5 利用space和layout_weight做占位**
124 | 有时候我们的需求很复杂,希望一个linearLayout中多个控件分散于两边,因为linearLayout内部的控件只能按照顺序依次排列,想要完成这个效果要用到`space`了。
125 | ```XML
126 |
127 |
134 |
135 |
142 |
143 |
148 |
149 |
154 |
155 |
156 | ```
157 | 
158 |
159 | 再举个常见的例子:
160 | 我们要做一个上面是viewpager,底部是tab栏的主页面。这种页面如果仅仅用linearLayout是没办法做的,但如果用了`layout_weight`就可以很方便的完成。
161 | ```XML
162 |
168 |
169 |
175 |
176 |
181 |
182 |
183 |
184 | ```
185 | 关键代码:
186 | ```XML
187 | android:layout_height="0dp"
188 | android:layout_weight="1.0"
189 | ```
190 | 
191 |
192 | **3.6 修改原生控件来支持实时预览**
193 | 上面也说到了,很多Android的原生控件都没为实时预览做优化,更不要说第三方的了。在最近的项目中我就遇到了用tabLayout做主界面tab栏的需求。但是google设计的tablayout的耦合性太高了,它依赖于一个viewpager,而viewpager又依赖于adapter,adapter又依赖于数据。所以完全没办法独立调试一个tablayout的样子。因此,我修改了它的代码,让其支持了布局的实时预览。主要就是加入了下面这段代码:
194 | ```JAVA
195 | private void preview(Context context, TypedArray a) {
196 | final String tabStrArr = a.getString(R.styleable.ExTabLayout_tools_tabStrArray);
197 |
198 | final String[] tabRealStrArr = getTabRealStrArr(tabStrArr);
199 | ViewPager viewPager = new ViewPager(context);
200 |
201 | viewPager.setAdapter(new PagerAdapter() {
202 | @Override
203 | public int getCount() {
204 | return tabRealStrArr.length;
205 | }
206 |
207 | @Override
208 | public boolean isViewFromObject(View view, Object object) {
209 | return view == object;
210 | }
211 |
212 | @Override
213 | public CharSequence getPageTitle(int position) {
214 | return tabRealStrArr[position];
215 | }
216 | });
217 | viewPager.setCurrentItem(0);
218 | this.setupWithViewPager(viewPager);
219 | }
220 | ```
221 | 你不是要viewpager么,我就给你viewpager。你不是要adapter么,我就给你adapter。你还要数据,好我也给你数据。值得注意的是,如果你这块代码是为了实时预览用,不想对真实的代码做任何影响,那么请务必用到`isInEditMode()`这个方法,比如上面的代码是这么调用的:
222 | ```JAVA
223 | // preview
224 | if (isInEditMode()) {
225 | preview(context, a);
226 | }
227 | ```
228 | 现在来看看效果吧:
229 | 
230 | 这种修改原生控件支持预览的做法没什么高深的,大家可以用类似的思路去改造那些难以预览的控件。
231 |
232 |
233 | **3.7 通过插件来进行动态预览**
234 | 我们都知道as的布局预览只支持静态预览,我们不能对预览界面进行交互,这样就无法测试滑动效果和点击效果了。所以我找到了[jimu mirror][1]这个插件来支持动态预览。启动mirror后,它会在你的手机上安装一个apk,这个apk展示的就是你当前的布局页面,mirror会监听xml文件的改动,如果xml文件发生了变化,那么它就能立刻刷新布局。下面来展示下我是如何在它的支持下预览viewpager的。
235 | 1. 首先在viewpager中加入这段代码
236 | ```JAVA
237 | private void preview(Context context, AttributeSet attrs) {
238 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExViewPager);
239 | List viewList = new ArrayList<>();
240 |
241 | int layoutResId;
242 | if ((layoutResId = a.getResourceId(R.styleable.ExViewPager_tools_layout0, 0)) != 0) {
243 | viewList.add(inflate(context, layoutResId, null));
244 | }
245 | if ((layoutResId = a.getResourceId(R.styleable.ExViewPager_tools_layout1, 0)) != 0) {
246 | viewList.add(inflate(context, layoutResId, null));
247 | }
248 | if ((layoutResId = a.getResourceId(R.styleable.ExViewPager_tools_layout2, 0)) != 0) {
249 | viewList.add(inflate(context, layoutResId, null));
250 | }
251 | if ((layoutResId = a.getResourceId(R.styleable.ExViewPager_tools_layout3, 0)) != 0) {
252 | viewList.add(inflate(context, layoutResId, null));
253 | }
254 | if ((layoutResId = a.getResourceId(R.styleable.ExViewPager_tools_layout4, 0)) != 0) {
255 | viewList.add(inflate(context, layoutResId, null));
256 | }
257 | a.recycle();
258 |
259 | setAdapter(new PreviewPagerAdapter(viewList));
260 | }
261 |
262 | /**
263 | * @author Jack Tony
264 | * 这里传入一个list数组,从每个list中可以剥离一个view并显示出来
265 | * @date :2014-9-24
266 | */
267 | public static class PreviewPagerAdapter extends PagerAdapter {
268 | private List mViewList;
269 |
270 | public PreviewPagerAdapter(List viewList) {
271 | mViewList = viewList;
272 | }
273 |
274 | @Override
275 | public int getCount() {
276 | return mViewList.size();
277 | }
278 |
279 | @Override
280 | public boolean isViewFromObject(View arg0, Object arg1) {
281 | return arg0 == arg1;
282 | }
283 |
284 | @Override
285 | public void destroyItem(ViewGroup container, int position, Object object) {
286 | if (mViewList.get(position) != null) {
287 | container.removeView(mViewList.get(position));
288 | }
289 | }
290 |
291 | @Override
292 | public Object instantiateItem(ViewGroup container, int position) {
293 | container.addView(mViewList.get(position), 0);
294 | return mViewList.get(position);
295 | }
296 |
297 | }
298 | ```
299 | 上面的工作是为xml中设置viewpager中页面的layout做支持,以达到预览的作用。
300 | 2. 编写xml布局文件
301 | ```XML
302 |
314 | ```
315 |
316 | 最后运行插件即可看到效果:
317 | 
318 |
319 | ### 四、快速预览插件
320 | 
321 | 上文提到了利用jimu mirror来做UI的实时预览,更多的预览技巧可以去他们的[网站][2]进行浏览。mirror做的是实时替换静态的xml文件,让开发者可以在真机中看到UI界面,感兴趣的朋友可以去试用体验版本的mirror。我在体验后感受到了它的强大和便捷,因为体验就几十天,所以我不得不成为了付费用户。其中最令人喜爱的是,他支持`tools`标签的属性并且支持力度强于as的实时预览器。
322 |
323 | 
324 | 与jimu mirror类似的,还有[jrebel][3]。这个东西更加强大,它做的不仅仅是让UI界面实时刷新,它甚至做到了让你更改java代码后就能实时替换apk中的类文件,达到应用实时刷新,我认为它是采用了热替换技术。官网的介绍是:Skip build, install and run,因此它可以节约我们很多很多的时间,它的效果也十分不错。
325 | jrebel和mirror的侧重点是不同的,它注重缩短应用整体的调试时间,走的仍旧是真机出结果的路线。而mirror目的是让开发者能实时预览UI,走的是UI独立测试的路线。总体来说这两款插件都挺不错的,这简直是给官方打脸啊。但因为jrebel太贵了,所以我还是推荐大家用mirror。
326 |
327 | ### 五、总结
328 | 这篇文章确实挺长的,也花了很多功夫。我仍旧觉得官方在设计和优化IDE上程序员思维太重,给开发者带来的便利还是太少。`tools`标签一直没代码提示、官方的控件的可预览性不友好等问题也使得开发者很难快速地进行UI调试。在如今Android世界MVP、MVVM等模式大行其道的今天,UI独立测试变得尤为重要,我不希望大家每次调试UI还得安装运行一遍apk,更加不希望看到as的实时预览功能变成鸡肋。
329 | 总之,感谢大家阅读到最后,如果你有其他的UI调试技巧请指出,如果你觉得本文提出的技巧有用,那么请尝试。
330 | 祝愿大家,中秋快乐~
331 |
332 | 示例代码下载:[http://download.csdn.net/detail/shark0017/9142445](http://download.csdn.net/detail/shark0017/9142445)
333 |
334 | ### 作者
335 | 
336 |
337 | developer_kale@qq.com
338 | @天之界线2010
339 |
340 | [1]: http://jimulabs.com/mirror-downloads/
341 | [2]: http://jimulabs.com/
342 | [3]: http://zeroturnaround.com/software/jrebel-for-android/
343 |
--------------------------------------------------------------------------------