Updating android Development Specification

Abstract

  • preface
  • AS the specification
  • Naming conventions
  • Resource file specification
  • Unified version specification
  • Third-party library specification
  • Annotation specifications
  • Test specification
  • RN specification
  • Some other specifications

preface

In order to facilitate the maintenance of the project and the development of the specification, and to promote the efficiency of Code Review among members, the following development specification is proposed. If you have better suggestions, please go to GitHub to propose an issue.

AS the specification

To do a good job, he must sharpen his tools.

  1. Develop with the latest version of the IDE whenever possible;
  2. The encoding format is UTF-8.
  3. After editing. Java and. XML files, be sure to format them (indent alignment is consistent with the default AS).
  4. Delete unnecessary imports to reduce warningsOptimize ImportsShortcuts;
  5. AS common development plug-ins can be referred to here ~ AS common development plug-ins

Naming conventions

1. The package name

Package names are all lowercase, and consecutive words are simply concatenated without underscores.

Use the anti – domain name naming rules, use all lowercase letters. The level-1 package name is a top-level domain name, usually com, edu, gov, net, org, etc. The level-2 package name is the company name, the level-2 package name is based on the application, and the level-4 package name is the module name or layer name.

The package name Contained in this package
Com.xx. Application name abbreviation. Activity All Activity classes in the user interface
Com.xx. Application name Abbreviation Fragment All Fragment classes in the interface
Com.xx. Application name abbreviation. Base The underlying shared class
Com.xx. Application name Abbreviation adapter The Adapter class used by the page (the Adapter class)
Com.xx. Application name abbreviation. View Custom View class
Com.xx. Application name abbreviation. Util This package contains: public utility method class (util module name)
Com.xx. Application name abbreviation. Bean Vo, Po, dTO This package contains: JavaBean class
Com.xx. Application name abbreviation. Model This package contains: model classes
Com.xx. Application name abbreviation. Db Database operation class
Com.xx. Application name abbreviation. View (or com.xx). Application name abbreviation. Widget) Custom View class, etc
Com.xx. Application name abbreviation. Service Service Service
Com.xx. Application name abbreviation. Receiver BroadcastReceiver service
Com.xx. application name abbreviation. Confing All configuration related classes

Note: If the project adopts MVP, all interfaces extracted from M, V, and P are placed under the I package of the corresponding module, and all implementations are placed under the IMPL of the corresponding module

2. The name of the class

Class names are written in UpperCamelCase style.

A class name is usually a noun or noun phrase, and an interface name may sometimes be an adjective or adjective phrase. There is no specific rule or well-established convention for naming annotation types.

For nouns, use the big hump nomenclature. Avoid abbreviations unless the abbreviations are well-known, such as HTML or URL. If the class name contains abbreviations, capitalize each letter of the abbreviations.

class describe For example,
The Activity class Activity is identified with a suffix The welcome page class WelcomeActivity
Adapter classes Adapter indicates the suffix identifier NewDetailAdapter NewDetailAdapter
Parsing class Parser indicates the suffix The home page parser class HomePosterParser
Tool method class Utils or Manager identifies a suffix (distinguished from system or third party Utils) or function +Utils Thread pool management class: ThreadPoolManager Log tool class: LogUtils (Logger also available) Print tool class: PrinterUtils
The database class It is identified with the DBHelper suffix News database: NewDBHelper
The Service class The suffix is Service Time service TimeServiceBroadcast
Receiver class The suffix “Receiver” is used JPushReceiver
ContentProvider The suffix is Provider
Custom shared base classes Starting with the Base BaseActivity,BaseFragment

The name of a Test class starts with the name of the class it is testing and ends with Test. For example, HashTest or HashIntegrationTest.

Interface: The same naming rules as classes use the big camel name, and most end with able or ible, such as interface Runnable and interface Accessible.

Note: If the project uses MVP, all Model, View, and Presenter interfaces are prefixed with I without suffix, and all other interfaces are named in the same way.

3. The method name

Method names are written in lowerCamelCase style.

Method names are usually verbs or phrasal verbs.

methods instructions
initXX() Initialize related methods, prefixed with init, such as initialize layout initView()
isXX() checkXX() If the return value of a method is Boolean, prefix it with is or check
getXX() A method that returns a value, prefixed with get
setXX() Sets a property value
handleXX()/processXX() A method of processing data
displayXX()/showXX() A dialog box and information are displayed. Use the prefix display/show to identify the information
updateXX() Update the data
saveXX() Save the data
resetXX() Reset the data
clearXX() Clear data
removeXX() Remove data or views, such as removeView();
drawXXX() Draw data or effects, identified with the draw prefix

4. Constant names

Constant names are named in CONSTANT_CASE, all uppercase letters, and words are separated by underscores. So, what exactly is a constant?

Each constant is a static final field, but not all static final fields are constants. When deciding whether a field is a constant, consider whether it really feels like one. For example, if the observed state of any of the instances is variable, it will almost certainly not be a constant. It’s generally not enough that you never intend to change an object, it has to really stay the same to show it as a constant.

// Constants
static final int NUMBER = 5;
static final ImmutableListNAMES = ImmutableList.of("Ed"."Ann");
static final Joiner COMMA_JOINER = Joiner.on(', '); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final SetmutableCollection = new HashSet();
static final ImmutableSetmutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these"."can"."change"};Copy the code

5. Name of the variable field

Variable field names are modified to the following style based on lowerCamelCase style: The basic structure is scopeVariableNameType.

Scope: the scope of

Non-public, non-static field names start with m.

Static field names start with s.

Public non-static field names start with P.

Public static field (global variable) names start with G.

Example:

public class MyClass {
      int mPackagePrivate;  
      private int mPrivate;  
      protected int mProtected;
      private static MyClass sSingleton;  
      public int pField;
      public static int gField;
}Copy the code

Use a one-character prefix to indicate the scope. The one-character prefix must be lowercase, followed by a name composed of one or more ideographic words. In addition, the first letter of each word is capitalized and the other letters are lowercase, which ensures that the variable name can be correctly delimited.

Type: Type

Considering the use of many UI controls in Android, in order to avoid confusion between controls and ordinary member variables and better meaning, all member variables used to represent controls are unified with control abbreviations as suffixes (with a list of abbreviations at the end of the article).

Generally, type suffixes are not added to common variables. If type suffixes are added uniformly, please refer to the abbreviation table at the end of this article.

By placing a quantifier at the end, you create more uniform variables that are easier to understand and search for.

Note: If ButterKnife is used in your project, do not add the m prefix and name it in the lowerCamelCase style.

For example, use mCustomerStrFirst and mCustomerStrLast instead of mFirstCustomerStr and mLastCustomerStr.

Quantifier list Quantifier suffix description
First The first of a set of variables
Last The last variable in a set
Next Next variable in a set of variables
Prev The last of a set of variables
Cur The current variable in a set of variables

Description:

Set add the following suffix: List, Map, Set Array add the following suffix: Arr

Note: All VO (value objects) are written in the standard lowerCamelCase style, and all Dtos (data transfer objects) are written according to the field names defined in the interface documentation.

6. The parameter name

Parameter names are written in lowerCamelCase style. Parameters should avoid single character names.

7. Local variable names

Local variable names are written in lowerCamelCase style and can have looser abbreviations than other types of names.

Although abbreviations are looser, avoid single-character names, except for temporary and circular variables.

Even if a local variable is final and immutable, it should not be shown as a constant, nor should it be named as a constant.

8. Temporary variables

Temporary variables, usually named I, j, k, m, and n, are used for integers; C, D, e, these are commonly used for character types. For (int I = 0; i < len ; I++).

9. Type variable name

Type variables can be named in one of two styles:

A single uppercase letter followed by a number (E, T, X, T2).

Use the class name (see 2. Class name) followed by a capital T(e.g. RequestT, FooBarT).

More also can refer to alibaba Java development manual

Resource file specification

1. Resource Layout file (XML file)

All lowercase, using the underscore naming method

1) the contentview

All words must be in lower case, underlined between words, using nouns or noun groups.

The contentView of any Activity or Fragment must correspond to its class name as follows:

Convert all letters to lowercase and switch types and functions (suffixes to prefixes).

For example: activity_main. XML

2) Dialog name:Dialog_ description. XML

For example: dialog_hint. XML

3) PopupWindow name:Ppw_ description. XML

For example: ppw_info. XML

4) List item naming:Item_ description. XML

For example: item_city. XML

5) Include item name:Module _(location) description.xml

For example, activity_main_head. XML and activity_main_bottom.xml

Note: The common include item names are: project name abbreviation _ description.xml

For example: xxxx_title. XML

2. Resource file (image drawable folder)

All lowercase, use the underscore naming method, prefix to distinguish

Naming mode: _small indicates a small image, _BIG indicates a large image, and the logical name can consist of multiple words and underscores. The following rules apply:

Usage _ Module name _ Logical Name Usage _ Module name _ Color Usage _ Logical name Usage _ Color

Description: Usage also charges piece type (see UI control abbreviation table for details)

Such as:

Btn_main_home. PNG buttons

Divider_maket_white. PNG divider

Ic_edit. PNG icon

Bg_main. PNG background

Btn_red. PNG Red button

Btn_red_big. PNG Big red button

Ic_head_small. PNG small head

PNG Background of the input box

Divider_white.png White dividing line

If you have multiple forms except for buttons like btn_xx.xml (selector)

The name of the function
btn_xx Button picture usageBtn_ Overall effect(the selector)
btn_xx_normal Button picture usageBtn_ Normal effect
btn_xx_pressed Button picture usageBtn_ effect when clicked
btn_xx_focused state_focusedFocus on results
btn_xx_disabled state_enabled(false) Effect not available
btn_xx_checked state_checkedSelect the effect
btn_xx_selected state_selectedSelect the effect
btn_xx_hovered state_hoveredHover effect
btn_xx_checkable state_checkableOptional effect
btn_xx_activated state_activatedActivation of
btn_xx_windowfocused state_window_focused
bg_head Background image useBg_ Function _ Description
def_search_cell Default image useDef_ Function _ Description
ic_more_help Icon image usageIc_ Function _ Description
seg_list_line Use pictures with separation featuresSeg_ Function _ Description
sel_ok Select icon to useSel_ Function _ Description

Note: using the plugin SelectorChapek from AndroidStudio you can quickly generate selectors, as long as you name them properly.

3. Animation file (under anim folder)

All lowercase, use the underscore naming method, prefix to distinguish.

The following rules are used for specific animations:

Module name _ Logical name

Logical name

refresh_progress.xml

market_cart_add.xml

market_cart_remove.xml

A normal Tween animation is named in the following table

// Start with the type of animation and end with the direction

Example of animation naming Specifications written
fade_in Fade in
fade_out Fade out
push_down_in Push in from the bottom
push_down_out Push from below
push_left To the left
slide_in_from_top Slide in from the head
zoom_enter Deformation into
slide_in Sliding into the
shrink_to_middle In the middle to narrow

4. Set values to name

1) colors.xml

The name of colors is named using the underscore naming method. In your colors.xml file, it should be just the name of the mapped color, an ARGB value, and nothing else. Do not use it to define ARGB values for different buttons.

Don’t do that

  <resources>
      <color name="button_foreground">#FFFFFF</color>
      <color name="button_background">#2A91BD</color>
      <color name="comment_background_inactive">#5F5F5F</color>
      <color name="comment_background_active"># 939393</color>
      <color name="comment_foreground">#FFFFFF</color>
      <color name="comment_foreground_important">#FF9D2F</color>.<color name="comment_shadow"># 323232</color>Copy the code

With this format, it is very easy to start redefining RGBA values, which makes it very complicated to change the base color if needed. Also, these definitions are associated with some environment, such as button or comment, and should be placed in a button style, not in a color.xml file.

Instead, do this:

  <resources>

      <! -- grayscale -->
      <color name="white"     >#FFFFFF</color>
      <color name="gray_light">#DBDBDB</color>
      <color name="gray"      ># 939393</color>
      <color name="gray_dark" >#5F5F5F</color>
      <color name="black"     ># 323232</color>

      <! -- basic colors -->
      <color name="green">#27D34D</color>
      <color name="blue">#2A91BD</color>
      <color name="orange">#FF9D2F</color>
      <color name="red">#FF432F</color>

  </resources>Copy the code

Ask the app designer for this palette. It doesn’t have to be named “green”, “blue”, etc. Names like “brand_primary”, “brand_secondary”, “brand_negative” are also perfectly acceptable. Standard colors like this are easy to modify or refactor, making it very clear how many different colors are used in the application. It is often important to reduce the number of colors used for a UI with aesthetic value.

2) dimens.xml

Treat dimens. XML like colors.xml and define a color palette, you should also define a “palette” of spacing and font sizes. A good example would look like this:

<resources>

    <! -- font sizes -->
    <dimen name="font_larger">22sp</dimen>
    <dimen name="font_large">18sp</dimen>
    <dimen name="font_normal">15sp</dimen>
    <dimen name="font_small">12sp</dimen>

    <! -- typical spacing between two views -->
    <dimen name="spacing_huge">40dp</dimen>
    <dimen name="spacing_large">24dp</dimen>
    <dimen name="spacing_normal">14dp</dimen>
    <dimen name="spacing_small">10dp</dimen>
    <dimen name="spacing_tiny">4dp</dimen>

    <! -- typical sizes of views -->
    <dimen name="button_height_tall">60dp</dimen>
    <dimen name="button_height_normal">40dp</dimen>
    <dimen name="button_height_short">32dp</dimen>

</resources>Copy the code

When writing margins and Paddings, you should use the spacing_xxxx size format to create layouts instead of writing values as you would for strings. Writing this way is very tactile and makes it very easy to organize and change style or layout.

3) strings.xml

The name of strings uses the underscore naming method and follows the following rules: module name + logical name

Such as:

Main_menu_about Main menu key Text friend_title Friend module title bar friend_dialog_del Friend deletion prompt login_check_email Login verification dialog_title Dialog box title Button_ok confirms that the key loaded the text

4) styles.xml

Almost every project needs to use a style file properly, because it is common for a view to have a duplicate look and feel. Put all the look and feel details (colors, padding, font) in the style file. For most text content in your app, you should at least have a common style file, for example:

<style name="ContentText">
    <item name="android:textSize">@dimen/font_normal</item>
    <item name="android:textColor">@color/basic_black</item>
</style>Copy the code

Apply to TextView:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/price"
    style="@style/ContentText"
    />Copy the code

You might want to do the same for button controls, don’t stop there. Put a set of related and repeating Android :**** attributes into a common style.

To split a large style file into multiple files, you can have multiple styles.xml files. The Android SDK supports other files, styles the file name does not have any effect, instead it uses the XML

5. Name the ID in layout

The naming mode is: View abbreviations _ module names _ logical names such as Btn_main_search use the AndroidStudio plugin ButterKnife Zelezny, which is handy for generating annotations, or you can use the Android Code Generator plugin.

If you want to subcontract resource files, you can refer to my article ~ Android Studio subcontract resources

Unified version specification

There are many different versions of Android development such as compileSdkVersion, minSdkVersion, targetSdkVersion and dependencies on third-party libraries in your projects. Different modules and developers can have different versions of these. So you need a uniform version of the specification file.

For details, please refer to this blog post I wrote ~ Unified Specification for Android Development

Third-party library specification

Let’s get out of the way and use the latest and hottest technology, amway’s popular Framework Checker, along with your own code that Android developers have to collect

It is hoped that the team can use the current relatively new technology. It is not recommended to build wheels by themselves or use wheels that have stopped maintenance, otherwise the issue cannot be raised if there is a problem.

Personal recommendations team use the Retrofit, RxAndroid OkHttp, Glide/Fresco, Gson/Fastjson, EventBus/AndroidEventBus GreenDao, (Dagger2, Tinker).

Annotation specifications

To make your code easy for others to read, make comments in key areas.

1. The class notes

Each class should be responsible for its own code, annotated with the author’s name and contact information.

/** * 
 * author: Blankj * E-mail: xxx@xx * time: 2017/03/07 * desc: XXXX Description * Version: 1.0 * 

*/Copy the code

For details, enter Setting → Editor → File and Code Templates → Includes → File Header in AS

** * 
 * Author: ${USER} * E-mail: xxx@xx * time: ${YEAR}/${MONTH}/${DAY} * desc: 1.0 * < / pre > * /


public class WelcomeActivity {... }Copy the code

This will automatically add the annotation every time you create a new class.

2. Method comments

Every member method (including custom member methods, override methods, and attribute methods) must have a method header comment. Type /** press enter in the first line of the method, and AS will generate the template for you.

/** * bitmap to byteArr **@paramBitmap Bitmap object *@paramThe format format *@returnByte array */
public static byte[] bitmap2Bytes(Bitmap bitmap, CompressFormat format) {
    if (bitmap == null) return null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(format, 100, baos);
    return baos.toByteArray();
}Copy the code

3. The piece of annotation

Block comments are indent at the same level as the surrounding code. They can be /*… */ style, also can be //… Style (// preferably followed by a space). For multiple lines /*… */ comment, subsequent lines must start with * and align with the * on the previous line. The following sample comments are OK.

/* * This is // And so /* Or you can * okay. // is this. * even do this. */* /Copy the code

Comments should not be enclosed in frames drawn by asterisks or other characters.

Tip: When writing multi-line comments, if you want to rewrap them if necessary, use /*… * /.

Test specification

After the completion of business development, developers do unit tests. After the completion of unit tests, ensure that all unit tests pass and the unit test code coverage reaches a certain level (this requires development and testing conventions, and the higher the better in theory), and develop and test.

// TODO…

RN specification

// TODO…

Some other specifications

  1. Reasonable layout, effective use<merge>.<ViewStub>.<include>The label
  2. Try to keep related methods together
  3. Don’t forget to detect memory leaks

The appendix

Table 1 UI control abbreviations

View abbreviations
TextView txt
EditText edit
Button btn
ImageButton ibtn
ImageView img
ListView lv
RadioGroup rgroup
RadioButton rbtn
ProgressBar rbar
SeekBar seek
CheckBox cb
Spinner spinner
TableLayout table
TableRow row
LinearLayout ll
RelativeLayout rl
ScrollView scroll
SearchView search
TabHost thost
TabWidget twidget

Table 2 Abbreviations of common English words:

The name of the abbreviations
icon IC (mainly used in app ICONS)
color Cl (mainly for color values)
divider Di (mainly used to divide lines, including not only dividers in the Listview but also lines in the regular layout)
selector Sl (mainly used for multiple states of a view, including not only the selector in the Listview, but also the selector of the button)
average avg
background Bg (mainly used as background for layouts and sub-layouts)
buffer buf
control ctrl
delete del
document doc
error err
escape esc
increment inc
infomation info
initial init
image img
Internationalization I18N
length len
library lib
message msg
password pwd
position pos
server srv
string str
temp tmp
window wnd(win)

Rule of abbreviations in programs: Do not use abbreviations unless the abbreviations are conventional.

reference

Android development best practices

Android Coding Specification

Alibaba Java Development Manual

Google Java Programming Style Guide

Version of the log

  • 17/03/06: version1.0, powered by Blankj(tsai)