Android代碼規範+小技巧
配置篇
layout的xml 命名 :以xml類型+”_”開頭
example:activity_Login.xml
fragment_home.xml
item_adapter_order.xml在xml使用xmlns:tools=http://schemas.android.com/tools ,方便調試,開發
除了text之外,還可以使用visiable等屬性xml控件規範
android:id 明顯應該在layout文件中第一行
android:style 放在最後一行單位
文字大小的單位應該統一用sp,其他元素用dp。因爲這兩個單位是與設備分辨率無關的,能夠解決在不同分辨率設備上顯示效果不同的問題。如果設置layout_weight=1 那麼你的layout_width或layout_height 就不要設置能“match_parent”,設置成0dp以便在測量時做出更好的優化
xml的根目錄爲時,可以用代替,因爲activity的父元素就是FrameLayout。當Inflate以開頭的佈局文件時,必須指定一個父ViewGroup,並且必須設定attachToRoot爲true(參看inflate(int,android.view.ViewGroup, Boolean)方法)
代碼篇
不要將Context 變量設置爲static
在activity中寫內部類,一定要把內部類設置爲static
保存sharedPreference時,建議用apply()代替commit()(不考慮線程安全的情況下);另外apply沒有返回值,而commit返回boolean表明修改是否提交成功;
遵守字段命名慣例:
非public的、非static的字段名稱以m開頭。
static字段名稱以s開頭。
其它字段以小寫字母開頭。
public static final字段(常量)全部字母大寫並用下劃線分隔。
//example
public class MyClass {
public static final int SOME_CONSTANT = 42;
public int publicField;
private static MyClass sSingleton;
int mPackagePrivate;
private int mPrivate;
protected int mProtected;
}
- 不要在底層的方法中處理異常,應該向方法的調用者拋出異常。