A brief talk on Android coding specification and naming specification

Source: Internet
Author: User

Text: A brief talk on Android code and naming specification

Objective:

The current work is responsible for the development of two medical app projects, while using Leancloud for cloud development, fully singled out.

The present large framework has been completed and is being developed on the details module

Take the time to summarize the development specifications for Android projects:1, Code Specification 2, naming conventions

  Note: Personal experience, for reference

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

One, the Android code specification

1. Learn to use String.xml files

In my opinion, when a text message appears more often than once, it must be used String.xml

For example, a save button, not the canonical wording :

<button            Android:id="@+id/editinfo_btn_save"            Android:layout_ Width="wrap_content"            android:layout_height="  Wrap_content"                   android:text= " save "            />

Here the text content is set to "save", then all the save buttons in an app are written like this. When one day to modify the requirements, the "save" text to change to "submit", then we can only go to a layout file changes,

It would be a waste of time and there might be a situation where the changes were missed.

  Standard wording:

<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 kind of writing, need to change later, only need to modify a line of code in the String.xml file to implement the whole app's text content modification.

  

2, learn to use Color.xml, the use of dimens.xml files

Consistent with the use of string.xml, students should all understand, do not because of a momentary lazy, resulting in later iterations of time-consuming effort.

  

3, team work together to determine a set of standard activity of the OnCreate () method of code execution process

In fact, when I first came into contact with Android, my nonstandard code was this:

PrivateButton Scan;//Scan button    PrivateButton Create;//Create button    PrivateArraylist<object> datas;//Data Source@Overrideprotected voidonCreate (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=NewArraylist<>(); Datas.add (NewInteger (1)); Datas.add (NewInteger (2)); Datas.add (NewInteger (3)); Datas.add (NewInteger (4)); }

  Whatever, all the operating code is written in the OnCreate () method, including the find control. Set up listening events, load data sources, and so on.

Can see now 2 control a data source, the code is so much, if an interface has more than 10 controls, then the OnCreate () method of the code in the number of multiples.

So all the activity has to set a uniform specification.

As we all know, there are basic operations in an activity:

①, initializing variables

②, initializing controls

③, setting Listener events

④, load network data and display

Then you can put the above code in the various categories of these methods

For example, a canonical code :

 Public classMainactivity extends Appcompatactivity implements View.onclicklistener {PrivateButton Btn_scan;//Scan button    PrivateButton btn_create;//Create button    PrivateArraylist<object> datas;//Data Source@Overrideprotected voidonCreate (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 the activity    Private voidinitvariables () {}//Load Data Source    Private voidLoadData () {}//Registering for monitoring events    Private voidinitevent () {Btn_scan.setonclicklistener ( This); Btn_create.setonclicklistener ( This); }    //Initializing the control    Private voidInitview () {btn_create=(Button) Findviewbyid (r.id.create); Btn_scan=(Button) Findviewbyid (R.id.scan); }    //set up Click events@Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btn_scan://Scan Two-dimensional codeStartActivity (NewIntent ( This, Scanactivity.class));  Break;  Caser.id.btn_create://generate two-dimensional codeStartActivity (NewIntent ( This, Createactivity.class));  Break; }    }}

Can see, onCreate () in just a few methods, we need to find the problem in the appropriate way to find can, both convenient and clear.

In fact, this kind of operation we can write a baseactivity as its abstract method, and then let the activity inherit this Baseactivity base class rewrite method, involving the schema, this later.

4, team work together to determine a control of the Click event Onclicklistener ()

Android gives us 5 ways to set the onclick for the control, and personally think that the most used item in the project is

①, parameter this and then activity implementation View.onclicklistener interface Rewrite OnClick () method

Btn_create.setonclicklistener (this);

②, the direct parameter of the new Onclicklistener ()

Btn_create.setonclicklistener (new  View.onclicklistener () {            @Override            public void OnClick (View v) {                            }        });

Three other methods the individual feels as far as possible not to use. The first of these two methods is better, because we can distinguish the click events of different controls with the Switch--case method, and the code is more concise and simple.

Of course, the second method is also possible, but it is best to remember that the same project has only one way to facilitate later maintenance.

//set up Click events@Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.scan://Scan Two-dimensional codeStartActivity (NewIntent ( This, Scanactivity.class));  Break;  Caser.id.create://generate two-dimensional codeStartActivity (NewIntent ( This, Createactivity.class));  Break; }    }

5, minimize the use of global variable static transfer value operation

Static characteristics everyone should know that he will always occupy a part of the memory, although very few, but a project of hundreds of thousands of use, the project is very bad.

Recommend the page between the value or use intent, to achieve no good solution for the re-use of static, PS, my previous company's project is very large use of static

Note: Some students may not be able to communicate with each other about activity and fragment, here is a solution: Android Project Combat (13): A brief talk about Eventbus, for me is the project must, but also to use reasonable

  

6. Try not to use internal classes in activity

Here to Recyclerview example, a very good control, with it no longer the ListView, talking about Recyclerview (perfect alternative to Listview,gridview)

A recyclerview is matched with a adapter and a viewholder.

    irregular Practices: Some students figure easy (of course, in an activity really convenient data transmission and item Click event operation), write them all in an activity, this is undesirable, because greatly increased the number of individual activity code, It's not convenient for maintenance.

    Standard practice: Viewholder A class, adapter a class, the Division of labor is clear, avoid the problem of too much code in a class.

Note: Listview,viewpager use ibid .  

As for class classification, some students like a function module placed under a package, such as a function point of activity, Adapter, Viewholder are placed under a package

Some students like a kind of put under a package, for example, put all the activity under the Activitys package, put all the adapter under the adapters package.

This is all something, in the future to learn the structure of the time to discuss

7, use ArrayList instead of HashMap

It is said that ArrayList use less memory than HashMap, because Android phones are uneven, so the development process of memory is very important, can save the province.

PS: The basic use of ArrayList in my project, unless it is a data structure that ArrayList cannot replace

8, the team standard Unified Third party

Now convenient and easy to use the third party too many, picture frame several excellent, push several excellent, instant communication several excellent.

Note using too many third parties can cause the program to be too large, and the application has a limit of the maximum number of methods, avoiding the ability of a third party to implement a feature, and the team members are using a different third party.

9. Unified Code Format

The classic is for loop, one is the left parenthesis at the end, one is another line. Unified, the interface looks comfortable, personal advice left parenthesis put in the last way, don't ask me why, university teacher recommended, Reason: forget.

 for (int0; i++) {                    }        for (int0; I ++)         {                    }

10, the different functions of the code should be separated by a line of space

Write a comment in conjunction, tell the maintenance classmate, which section of the code is what to do

For the code clear also in order to maintain the classmate less two hair length.

11. If you are developing Android studio

Please use CTRL + a frequently-+alt + I

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

Second, the Android naming specification

Naming specification: Hump method, Underline segmentation method.

1. Java class files

①, activity: With activity as the suffix, this believes everyone as to you to help you do well.

②, Adapter: with Adapter as suffix

③, Viewholder: with Viewholder as suffix

④, entity class entity: with entity as suffix

   

As below, I am a function Module sub-package, big God do not spray, personal preferences:

  

2. xml file

①, Layout.xml

The activity's layout file begins with Activity_, as provided by the.

Layout file for list items The ListView starts with Item_list_.

②, naming of controls

Abbreviation, this looks personal,

My experience, for example:

Layoutview----LV

TextView----TV

Button----BTN

ImageView----img

  Remember, do not use pinyin naming, even if the English dish of bloggers I developed all open Youdao dictionary.

Finally, the code must write the comments, you name if the English is not immediately able to understand, please make sure to write the comments.

Comment!

Comments!

Comments!

A brief talk on Android coding specification and naming specification

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.