部分参考自:http://www.hawstein.com/posts/google-java-style.html
1、宏定义:使用static final修饰,名字全大写
private static final int PICK_IMAGE_REQUEST_CODE = 100;
2、常量写在类的最前面,变量写在常量后面
3、打印log情形:
- 格式:前缀使用应用名加下划线,Sdk使用应用名加Sdk加下划线,TAG使用类名;
比如日历应用:Calendar_CalendarApplication
- 有异常,提前返回时打印,正常逻辑一般不打,视情况而定:
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
LogUtil.e(TAG, "terrible, am is null!");
return;
}
- 捕获异常:禁止调用系统接口printStackTrace():参考https://developer.android.com/reference/android/util/Log.html
try {
} catch (Exception e) {
//e.printStackTrace(); 禁止使用
LogUtil.e(TAG, "something is exception : " + e.toString());
}
4、重写父类接口:加上@Override, 方便理解;
5、判断语句执行的代码块,必须加上{},即使只有一行,包括if、while、switch...case等:
boolean find = false;
if(state) {
find = true;
}
6、switch...case语句必须加上default操作:
switch(state) {
case state0: {
break;
}
default : {
break;
}
}
7、内部类放在类的最后面,接口放在变量后面,构造方法前面。
8、实现了父类接口的变量放在一般变量后面,函数前面:
private EditText mEditText;
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
default:{
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
9、避免使用静态变量;
10、每次只声明一个变量;
11、类名或接口通常是名词或名词短语,第一个字母大写;
12、方法名通常是动词或动词短语,第一个字母小写;
13、参数名:参数应该避免用单个字符命名。
14、字符串的连接:超过两个字符串的连接,使用StringBuilder或StringBuffer(同步)。
15、代码格式化使用Android Studio默认即可。
