Code Monkey home page Code Monkey logo

coding_convention_android's Introduction

Coding convention Android

1. Quy tắc đặt tên file

1.1 Đặt tên lớp

  • Tên lớp viết dạng UpperCamelCase. (Là danh từ, và viết hoa tất cả các chữ cái đầu,...).
  • Nếu lớp mà được extend từ một lớp thành phần của Android thì tên lớp phải được kết thúc bằng tên của lớp thành phần này. Ví dụ: SignInActivity, SignInFragment, ImageUploaderService, ChangePasswordDialog.

1.2 Đặt tên Resource files

Cấu trúc chung viết theo dạng lowercase_underscore (viết thường, phân cách bởi dấu gạch dưới)

1.2.1 Drawable files

Asset Type Prefix Example
Action bar ab_ ab_stacked.9.png
Button b_ b_send_pressed.9.png
Dialog dialog_ dialog_top.9.png
Divider divider_ divider_horizontal.9.png
Icon ic_ ic_star.png
Menu menu_ menu_submenu_bg.9.png
Notification notification_ notification_bg.9.png
Tabs tab_ tab_pressed.9.png

Nếu drawable thuộc loại selector thì trạng thái selector sẽ được đặt cùng hậu tố như sau

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.2.2 Layout files

Tên của Layout nên bắt đầu bằng tên của Android components sẽ sử dụng nó, theo sau là tên của class sẽ sử dụng nó.

Lưu ý:

  • Nếu Layout được sử dụng như là một phần của Adapter hoặc ListView thì tên Layout sẽ bắt đầu bằng item_.
  • Nếu Layout là một phần của Layout khác thì tên sẽ được bắt đầu bằng partial_.

Ví dụ:

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.2.3 Menu files

Tên của menu file được đặt tương tự như Layout file: Bắt đầu bằng tên của Android component sẽ sử dụng nó và theo sau là, theo sau là tên của class sẽ sử dụng nó. Lưu ý là không đính kèm từ menu vào phần tên vì mặc định những file này đã nằm trong thư mục menu. Ví dụ tên lớp UserActivity thì menu file sẽ được đặt là activity_user.xml.

2. Quy tắc trong code Java

2.1 Đặt tên biến

Việc định nghĩa các biến luôn được đặt ở đầu file và theo các quy tắc sau:

  • Biến private, non-static tên bắt đầu bằng m
  • Biến private, static tên bắt đầu bằng s
  • Các biến khác viết thường chữ cái đầu, các từ tiếp theo viết hoa chữ cái đầu
  • Biến là hằng thì viết hoa toàn bộ và phân cách bằng dấu gạch dưới
  • Những từ viết tắt thì tất cả các chữ cái của từ đó phải viết hoa

Ví dụ:

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;
}
Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
String url String URL
long id long ID

Có các thành phần trong Android sử dụng các cặp Key-value như SharedPreferences, Bundle, hay Intent. Khi sử dụng những thành phần này các Key phải được định nghĩa là các hằng số dạng static final và tên được bắt đầu như sau:

Element Field Name Prefix
SharedPreferences PREF_
Bundle BUNDLE_
Fragment Arguments ARGUMENT_
Intent Extra EXTRA_
Intent Action ACTION_

Ví dụ:

// Note the value of the field is the same as the name to avoid duplication issues
static final String PREF_EMAIL = "PREF_EMAIL";
static final String BUNDLE_AGE = "BUNDLE_AGE";
static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID";

// Intent-related items use full package name as value
static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME";
static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER";

2.2 Đặt Log

Lấy tên lớp làm giá trị cho Tag trong hàm ghi Log. Tag thường là hằng và được định nghĩa ở đầu lớp.

Các loại log như VERBOSE hay DEBUG chỉ được sử dụng trong bản debug, trong bản release sẽ phải loại bỏ

Ví dụ:

public class MyClass {
    private static final String TAG = MyClass.class.getSimpleName();

    public myMethod() {
        Log.e(TAG, "My error message");
	if (BuildConfig.DEBUG) Log.d(TAG, "mesage");
    }
}

2.3 Thứ tự đặt tham số trong phương thức

Trong các phương thức biến Context(nếu có) thì luôn đặt ở đầu trong danh sách tham số, ngược lại các biến callback(nếu có) luôn đặt ở cuối

Ví dụ:

// Context always goes first
public User loadUser(Context context, int userId);

// Callbacks always go last
public void loadUserAsync(Context context, int userId, UserCallback callback);

2.4 Giới hạn độ dài trên một dòng

Một dòng không nên dài quá 100 ký tự. Nếu một dòng mà dài hơn giới hạn này thì có 2 cách để giảm số ký tự xuống:

  • Extract a local variable or method (preferable).
  • Chia 1 dòng thành nhiều dòng

Ví dụ:

int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
        + theFinalOne;

Picasso.with(context)
        .load("http://ribot.co.uk/images/sexyjoe.jpg")
        .into(imageView);

loadPicture(context,
        "http://ribot.co.uk/images/sexyjoe.jpg",
        mImageViewProfilePicture,
        clickListener,
        "Title of the picture");

3. Quy tắc trong file XML

3.1 Đặt tên Resources

Cấu trúc chung viết theo dạng lowercase_underscore (viết thường, phân cách bởi dấu gạch dưới)

3.1.1 Tên ID

Tên ID bắt đầu bằng chữ viết tắt của view. Ví dụ:

Element Prefix
TextView tv_
ImageView iv_
Button b_
Menu m_
CheckBox cb_

3.1.2 Đóng tag

Nếu một phần tử XML mà không có nội dung thì phải đóng tag ngay trong thẻ mở. Ví dụ:

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

3.2 Thứ tự đặt các thuộc tính trong thẻ XML

  1. View Id
  2. Style
  3. Layout width and layout height
  4. Other layout attributes, sorted alphabetically
  5. Remaining attributes, sorted alphabetically

coding_convention_android's People

Contributors

nguyenvulebinh avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.