Talking about Android coding standards and naming standards, talking about android coding standards

Source: Internet
Author: User
Tags coding standards

Talking about Android coding standards and naming standards, talking about android coding standards

Preface:

At present, I am responsible for the development of two medical APP projects. At the same time, I am using LeanCloud for cloud-based development.

Now the big framework has been completed and is under development in the detail module.

Summarize the development specifications of Android projects: 1. coding Specifications 2. Naming rules

Note: personal experience, for reference

Bytes --------------------------------------------------------------------------------------------------------------------------

I. Android coding specifications

1. Learn to use the string. xml file

In my opinion, when a text message appears more than once, you must use string. xml

For example, a Save button is not written as follows:

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

Set the text content to "save". All the save buttons in an app are written in this way. If you need to modify the text one day and change the "save" text to "Submit", you can only modify the text in one layout file,

Do not waste a lot of time and there may be situations where modifications are missed.

Standard writing:

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

In the string. xml file:

<String name = "save"> save </string>

This method needs to be modified later. You only need to modify a line of code in the string. xml file to modify the text content of the entire APP.

  

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

Similar to the use of string. xml, you should understand it. Do not be lazy at the moment, resulting in time-and effort-consuming later iterations.

  

3. The team works together to determine the Code Execution Process in the onCreate () method of a standard Activity.

In fact, when I first got started with Android, my nonstandard 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 it is, all the operation code is written in the onCreate () method, including the find control. Set listening events and load data sources.

Now we can see that there are only two controls and one data source, so there is so much code. If there are more than 10 controls on one interface, then onCreate () the amount of code in the method is a multiple.

Therefore, a unified specification must be set for all activities.

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

① Initialization Variables

② Initialize the control

③ Set listening events

④ Load and display network data

Then we can classify the above Code into several methods.

For example, a piece of standard 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 () ;}// initialization variable, for example, the Intent data from the previous Activity. Some private void initVariables () {}// load the data source private void loadData (), such as marking variables, in this Activity () {}// register the listener event 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 the QR code startActivity (new Intent (this, ScanActivity. class); break; case R. id. btn_create: // generate the QR code startActivity (new Intent (this, CreateActivity. class); break ;}}}

As you can see, there are just a few methods in onCreate (). When we need to find the problem, we can find it in the corresponding method, which is convenient and clear.

In fact, we can write a BaseActivity as its abstract method, and then let the Activity inherit the BaseActivity base class rewrite method, which involves the architecture. Let's talk about it later.

 

4. The team works together to determine the OnClickListener () event of a control ()

Android provides five methods for setting OnClick for controls.

①. The parameter this is then used by the Activity to implement the View. OnClickListener interface and override 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 are recommended. The first of the two methods is better, because we can use the switch -- case Method to differentiate click events of different controls, and the code is clearer and simpler.

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

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

 

5. Use static global variables as few as possible for value transfer

We should all know about the static feature. It will always occupy part of the memory. Although it is rare, it is very bad for a project if there are hundreds of users in a project.

We recommend that you use Intent to transfer values between pages to achieve static and PS solutions without any good solutions. Previously, my company used a lot of static projects.

Note: Some students may not pass values to each other during Activity and Fragment. Here we recommend a solution: Android Project Practice (13th): Talking about EventBus, which is a required project for me, but it should also be used properly.

  

6. Try not to use internal classes in Activity

Here, we use RecyclerView as an example. It is a very good control and does not need ListView anymore. Let's talk about RecyclerView (perfect alternative to ListView and GridView)

A RecyclerView is composed of an Adapter and a ViewHolder.

Non-standard practice: Some students save time (of course, it is really convenient to put data in an Activity and operate on item click events) and write them in an Activity. This is not advisable, this greatly increases the amount of code for a single Activity, which is inconvenient for maintenance.

Standard Practice: ViewHolder is a class and Adapter is a class with a clear division of labor to avoid excessive code in a class.

Note: ListView and ViewPager use the same as above

For classification of classes, some people like to put a function module under a package, such as a function Activity, Adapter, and ViewHolder under a package.

Some students like to put one type under one package. For example, they put all the activities under the activitys package and put all the adapters under the adapters package.

This is a post, and we will discuss it in detail in the future.

 

7. Use ArrayList instead of HashMap

It is said that ArrayList uses less memory than HashMap, because android phones are uneven, so the memory is very important in the development process, saving time.

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

 

8. Third parties with standardized teams

There are too many convenient and easy-to-use third parties. There are several excellent image frameworks, several excellent push products, and several excellent instant messaging products.

If you use too many third parties, the program will be too large, and the application has a maximum number of methods to avoid third parties that implement a function. Team members use different third parties.

9. unified code format

Classic is the for loop. One is to put the left parenthesis at the end, and the other is to start a row. In a unified manner, the interface looks comfortable. I personally suggest placing the left brackets at the end of the way. Don't ask me why, recommended by a college teacher. Reason: Forget.

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

 

10. Separate code with one line of space.

Write comments in coordination to inform maintenance personnel of the operations performed on the code.

For sake of code clarity, and for maintenance, two hairs are less long ..

11. If you are using Android Studio

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

Bytes --------------------------------------------------------------------------------------------------------------------------

Ii. Android naming rules

Naming rules: hump and underline.

1. Java files

1. Activity: use Activity AS the suffix. I believe that all the content you have provided AS is ready for you.

② Adapter: Use Adapter as the suffix

③ ViewHolder: Use ViewHolder as the suffix

④ Entity: the object class uses Entity as the suffix

   

As shown in the following figure, I subscribe to the function module, so do not spray it. My personal preferences:

  

2. xml file

① Layout. xml

The layout file of the Activity starts with activity _, which is provided by.

The layout file listview of the list item starts with item_list.

② Control naming

Abbreviation: This is my name,

My experience, such:

LayoutView ---- lv

TextView ---- TV

Button ---- btn

ImageView ---- img

 

Remember, do not use Pinyin names, even if I have a dictionary in the development of English bloggers.

Finally, you must write comments for coding. If the English name you name cannot be understood immediately, write comments.

Note!

Note!

Note!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.