Talking about Android coding standard and naming standard

Original: Talking about Android Coding Standards and Naming Standards

Foreword:

  At present, I am responsible for the development of two medical APP projects. At the same time, I use LeanCloud for cloud cooperation development, which is completely singled out.

  The big framework has been completed, and the development of the detailed modules is in progress

  Take the time to summarize the development specifications of the Android project: 1. Coding specifications 2. Naming specifications  

  Note: Personal experience is for reference

--------------------------------------------------------------------------------------------------------------------------

1. Android coding standard

  1. Learn to use the string.xml file

  In my opinion, string.xml must be used when a text message occurs more than once

  For example, a save button, not standardized writing :

      <Button
            android:id="@+id/editinfo_btn_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"       
            android:text="保存"
            />

  Here the text content for it is set to "Save", then all the save buttons in an app are written like this. When we need to modify the requirements one day and ask to change the "save" text to "submit", then we can only modify it in one layout file.

  Wouldn't it waste a lot of time and there may be missed changes.

  Standard writing:

      <Button
            android:id="@+id/editinfo_btn_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"       
            android:text="@string/save"
            />

  And in the string.xml file:

    <string name="save">保存</string>

  This writing method needs to be modified in the future. Only one line of code needs to be modified in the string.xml file to realize the modification of the text content of the entire APP.

  

  2. Learn to use color.xml and dimens.xml files

  The use of string.xml is consistent with that of string.xml. Students should all understand it. Don’t make later iterations time-consuming and labor-intensive because of temporary laziness.

  

  3. The team cooperates to determine the code execution process in the onCreate() method of a standard Activity

  In fact, when I first came into contact with Android, my non-standard code was like this:

   private Button scan;             // Scan button 
    private Button create;           // Create button 
    private ArrayList<Object> datas; // Data source @Override 
protected void onCreate(Bundle     savedInstanceState
     ) { 
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        create = (Button) findViewById(R.id.create);
        scan = (Button) findViewById(R.id.scan);
        scan.setOnClickListener(this);
        create.setOnClickListener(this);
        datas = new ArrayList<>();
        datas.add(new Integer(1));
        datas.add(new Integer(2));
        datas.add(new Integer(3));
        datas.add(new Integer(4));
    }

  No matter what, all the operation code is written in the onCreate() method, including the find control. Set up listener events, load data sources, and more.

  It can be seen that there are only 2 controls and one data source, and the code is so much. If there are more than 10 controls in an interface, the amount of code in the onCreate() method will be multiplied.

  Therefore, all activities must set a unified specification.

  We all know that there are basically operations in an Activity:

    ①、Initialize variables

    ②, initialize the control

    ③, set the monitoring event

    ④, load network data and display

  Then the above code can be classified into these methods

  For example, a canonical code :

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_scan;             // Scan button 
    private Button btn_create;           // Create button 
    private ArrayList<Object> datas; // Data source 
    @Override
     protected  void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        initVariables();
        initView();
        initEvent();
        loadData();
    }

    // Initialize variables, such as the Intent data from the previous Activity, some tag variables in this Activity, etc. 
    private  void initVariables() {

    }

    // Load data source 
    private  void loadData() {
    }

    // Register listener events 
    private  void initEvent() {
        btn_scan.setOnClickListener(this);
        btn_create.setOnClickListener(this);
    }

    // Initialize the control 
    private  void initView() {
        btn_create = (Button) findViewById(R.id.create);
        btn_scan = (Button) findViewById(R.id.scan);
    }

    // Set the click event 
    @Override
     public  void onClick(View v) {
         switch (v.getId()){
             case R.id.btn_scan:
                 // Scan QR code 
                startActivity( new Intent( this ,ScanActivity.class ) );
                 break ;
             case R.id.btn_create:
                 // Generate QR code 
                startActivity( new Intent( this ,CreateActivity. class ));
                 break ;
        }
    }
}

    It can be seen that there are only a few methods in onCreate(). When we need to find a problem, we can find it in the corresponding method, which is convenient and clear.

    In fact, for this kind of operation, we can write a BaseActivity as its abstract method, and then let Activity inherit the BaseActivity base class to override the method. It involves the architecture, which will be discussed later.

 

  4. The team cooperates to determine the click event OnClickListener() of a control

    Android provides us with 5 ways to set OnClick for controls. Personally, I think the most used in the project is

   1. Parameter this and then Activity implements  the View.OnClickListener interface and rewrites the onClick() method

 

btn_create.setOnClickListener(this);

     ②, the direct parameter of new OnclickListener()

btn_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });

   The other three methods personally feel that try not to use. The first of these two methods is better, because we can distinguish the click events of different controls through the switch--case method, and the code is clearer and simpler.

     Of course, the second method is also possible, but remember that there is only one method in the same project, which is convenient for later maintenance.

  // Set the click event 
    @Override
     public  void onClick(View v) {
         switch (v.getId()){
             case R.id.scan:
                 // Scan QR code 
                startActivity( new Intent( this ,ScanActivity.class ) );
                 break ;
             case R.id.create:
                 // Generate QR code 
                startActivity( new Intent( this ,CreateActivity. class ));
                 break ;
        }
    }

 

    5. Minimize the use of global variables static for value-passing operations

    Everyone should know the static feature. It will always occupy a part of the memory. Although it is very small, it is very bad for the project if it is used by hundreds or thousands in a project.

    It is recommended to use Intent for the value transfer between pages, to realize the reuse of static without a good solution, PS, my previous company's projects have used static a lot. 

         Note: Some students may not have a good idea of ​​the mutual value transfer between Activity and Fragment. Here is a solution recommended: Android project combat (13): Talking about EventBus  , it is a must for the project for me, but it should be used reasonably

  

  6. Try not to use inner classes in Activity

    Here is an example of RecyclerView, a very good control. With it, ListView is no longer needed. Talking about RecyclerView (perfect replacement for ListView, GridView)

    A RecyclerView is matched with an Adapter and a ViewHolder.

    Irregular practice: some students take pictures to save trouble (of course, putting them in an Activity is really convenient for data transmission and item click event operation), and writing them all in one Activity is not desirable, because the code of a single Activity is greatly increased. It is very inconvenient for maintenance.

    Standard practice: ViewHolder is a class, Adapter is a class, and the division of labor is clear to avoid the problem of too much code in one class.

    Note: ListView, ViewPager use the same as above 

    As for the classification of classes, some students like to put a functional module under one package, such as Activity, Adapter and ViewHolder of a function point are all placed under one package

                               Some students like to put one class under one package, for example, put all Activities under the activities package, and put all Adapters under the adapters package.

    This is a later story, and I will discuss it in detail when I learn the architecture in the future.

 

  7. Use ArrayList instead of HashMap

     It is said, it is said that the memory used by ArrayList is lower than that of HashMap, because android phones are uneven, so memory is still very important in the development process, and it can be saved if possible.

    PS: ArrayList is basically used in my project, unless it is a data structure that ArrayList cannot replace

 

  8. A third party with unified team norms

     There are too many convenient and easy-to-use third parties. There are several excellent picture frames, several excellent ones for push, and several excellent ones for instant messaging.

     Note that using too many third parties will cause the program to be too large, and the application has a limit on the maximum number of methods, avoiding third parties that implement a function, and team members use different third parties.

   

  9. Unified code format

    The classic is the for loop, one is to put the left parenthesis at the end, and the other is to start a new line. Under the unified, the interface looks comfortable. I personally suggest that the left parenthesis should be placed at the end. Don't ask me why. The university teacher recommended it. Reason: I forgot.

     for (int i = 0; i < 10; i++) {
            
        }
        for (int i = 0; i < 10; i++) 
        {
            
        }

 

  10. There should be a line of spaces between different function codes

    Cooperatively write a comment to tell the maintenance classmates which piece of code is doing what operation 

    For the clarity of the code and the maintenance of the classmates, two hair less. .

   

  11. If you are developing with Android Studio

    Please use Ctrl+A frequently --> Ctrl +Alt + I  

--------------------------------------------------------------------------------------------------------------------------

2. Android naming convention

  Naming conventions: camel case, underscore segmentation.

  1. Java class file

  ①, Activity: with Activity as the suffix, I believe that everyone AS gave you will help you do it well.

  ②, Adapter: Adapter as the suffix

  ③, ViewHolder: Take ViewHolder as the suffix

  ④, entity class Entity: Entity as the suffix

   

  As follows, I am subcontracting with functional modules, please do not spray, personal preference:

  

  2. xml file

  ①、layout.xml

    Activity's layout file starts with activity_, provided by AS.

    The layout file listview for list items starts with item_list_.

  ②, the naming of the control

    Abbreviation, this depends on the individual,

    My experience such as:

    LayoutView    ----    lv

    TextView        ----    tv

           Button          ----    btn

    ImageView     ----    img

 

  Remember, don't use pinyin names, even if the bloggers who are so good in English have developed a Youdao dictionary.

  Finally, the coding must be written with comments. If the English you name is not immediately understandable, please be sure to write a comment.

     

   Comment!

  Comment!

   Comment!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325069272&siteId=291194637