关于Android开发的那些事儿Android知识Android开发

Android 代码规范

2017-05-03  本文已影响106人  Bear_android

1 文件命名

1.1 类文件命名 参考.

类命名方式采用 大驼峰 命名法

对于继承自安卓组件的类来说,类名应该以该组件名结尾,例如 : SignInActivity, SignInFragment, ImageUploaderService, ChangePasswordDialog.

对于工具类来说,命名方式应该以其完成功能开始,以 Utils 结束 ,例如 :HttpUtils , ImageUtils.

1.2 资源文件

资源文件以小写加下划线的方式命名.例如 :R.layout.activity_main ,

1.3 Drawable文件

Asset Type Prefix 前缀 Example
Icons ic_ ic_star.png
Launcher icons ic_launcher ic_launcher_calendar.png
Menu icons and Action Bar icons ic_menu ic_menu_archive.png
Status bar icons ic_stat_notify ic_stat_notify_msg.png
Tab icons ic_tab ic_tab_recent.png
Dialog icons ic_dialog ic_dialog_info.png
State Suffix 尾缀 Example
Normal _normal btn_order_normal.9.png
Pressed _pressed btn_order_pressed.9.png
Focused _focused btn_order_focused.9.png
Disabled _disabled btn_order_disabled.9.png
Selected _selected btn_order_selected.9.png

1.4 布局文件

布局文件的命名需要与他所嵌入的安卓组件匹配,但是将组件名称前移到开始处,例如,我们要创建一个名字为 SignInActivity, 其名字应该为 activity_sign_in.xml.

Component 组件 Class Name Layout Name
Activity UserProfileActivity activity_user_profile.xml
Fragment SignUpFragment fragment_sign_up.xml
Dialog ChangePasswordDialog dialog_change_password.xml
AdapterView Item --- item_person.xml

1.5 类变量命名

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;
}

1.6 类方法命名

   /**
    * 获取两个数中最大的一个
    *
    * @param value1 参与比较的第一个数
    * @param value2 参与比较的第二个数
    * @return 两个参数中最大的一个数
    */
   public int max(int value1, int value2) {
       return (value1 > value2) ? value1 : value2;
   }

1.7 布局文件变量命名

Component 组件 Abbreviation 缩写
Fragment fgm
TextView tv
ImageView iv
Button btn
EditText et
LinearLayout ll
ReleativeLayout rl
normally : FirstSecond fs

1.8 strings.xml dimens.xml colors.xml xml变量命名

  • 遵循 完整性 规范性 有序性原则
Prefix 前缀 Description 描述
error_ An error message
msg_ A regular information message
title_ A title, i.e. a dialog title
action_ An action such as "Save" or "Create"

1.9 额外注意

Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
String url String URL
long id long ID

2 代码规范


This is good

if (condition){
    body();
}

This is bad:

if (condition) body();  // bad!

This is good:

<TextView
    android:id="@+id/text_view_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

This is bad :

<!-- Don't do this! -->
<TextView
    android:id="@+id/text_view_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>
上一篇 下一篇

猜你喜欢

热点阅读