I summarize the Android programming specification

Source: Internet
Author: User

Naming rules

1). class name, Interface name:
Starting with uppercase, if the class name of a class consists of multiple words, the first letter of all the words must be capitalized, the word should be written as full as possible, not abbreviated, unless the customary name, for example: URL,RTMP,RTSP these widely used proper nouns, can be all uppercase, can also capitalize the first letter.
such as Httprequest,courseactivity

2). Local variables, member variables of a class, member functions of a class, function arguments:
Starting with the first letter of the other words in lowercase letters, variable names do not recommend the use of underscores to separate words, it is recommended to use the Camel name method, Android system class use this method.
For example, toString () Oncreateview (Bundle savedinstancestate)

3). Static constants: All uppercase, the words are separated by underscores, and the constant words are all capitalized, so the words are separated by underscores.
such as What_empty_content

4). Name of the control variable, name of the control's ID:
Recommendation: The ID of the control in the XML layout file is named in the same name as the control object in the *.java code file.

Class  myactivity extends Activity{textview  txtusername  ; protected void OnCreate (Bundle savedinstancestate) {txtusername =  (TextView) Findviewbyid (R.id.txtusername);}}

5). Specification description for common controls and class object naming (the red part is the suggested prefix or suffix):

Class name

Variable name

Class name

Variable name

TextView

txt Description

ProgressBar

Progress Description

Button

btn Description

SeekBar

SeekBar Description

ImageButton

imgbtn Description

Videoview

VV Description

ImageView

img Description

Spinner

Spin Description

RadioButton

RB Description

WebView

WebView Description

EditText

Edit Description

Listview

ListView Description

ScrollView

Scroll Description

Gridview

Grid Description

Handler

DescriptionHandler

Ratingbar

Ratingbar Description

Pulltorefreshlistview

Pullrefreshview Description

Adapter

DescriptionAdapter

Fragment

DescriptionFragment

Activity

DescriptionActivity

List<t>

DescriptionList

Map<>

Map Description

Slidingmenu

Slidmenu Description

Viewpager

Viewpager Description

CheckBox

Chbox Description

View

View Description

Radiogroup

RG Description

Expandablelistview

Exp Description

Framelayout

Framelay Description

Sharedpreferences

SP Description

LinearLayout

Linelay Description

Relativelayout

Relativelay Description

Startactivityforresult (Requestcode)

Request_code_description

Msg.what

What _description

6). Resource naming:
Name of the layout resource file (all lowercase, underscore delimited):
Resource files for activity:Activity_description1_description2.xml
Resource files for fragment:Fragment_description1_description2.xml
Resource file for ListView list item:List_item_description1_description2.xml
Reusable (include) component resource files:Control_description1_description2.xml
Drawable Resources:controlname_description1_description2_selector. xml
ControlName indicates what type of control the resource is to be used on, for example, if the button's picture toggle
It should be defined Button_bg_sendmessage_selector.xml
Selector represents the form of the resource, for example, shape, etc.
Name of picture resource: Ibid.
Name of the color value:ColorThe _description is prefixed with color, all lowercase and underlined. Description can be either a functional description of the color value or an English description of the color value, or it can be a specific color value, for example:
<color name= "Color_white" > #ffffff </color>
<color name= "COLOR_GREY_CCC" > #cccccc </color>
<color name= "color_grey_ddd" > #dddddd </color>
Because Grey may have many grades, sometimes require different levels of gray, not so many English names can be distinguished, so the name can be directly used in the color value
<color name= "color_button_pressed" > #4c4c4c </color> defines description by function, indicating that the color is used for the button being pressed

Note: No meaningless naming is allowed, such as Textview1,textview2

About literal constants

Direct hard-coded literal constants are not allowed in the code, and if the text is displayed above the control, it must be placed in the Strings.xml resource file. If you are using a constant string in your code, you must define a constant value of public static final string to use the defined constant value in your code. The advantage of this is that you need to modify the constant value later, and you need to modify only one place. If it is hardcoded in the code, you have to modify all the places where it is used, and the copy is error-prone. When passing parameters between activity, the key value of Intent.putextra is also named specification, and is uniformly defined as a static constant, not directly hardcoded in the code, or want to modify the time is very troublesome. When an activity needs to accept parameters when it is started, the key definition of these parameters should be placed in the activity.

JSON parsing

The interface of the call server in Android generally returns JSON data, when parsing JSON, whether using the original manual parsing method, or using JavaBean parsing method, the parsed result must be empty processing when used. Does not allow problems with JSON on the server, causing the app to crash when parsing json.

Class member initialization

The member variables of all classes must be assigned initial values, not allowed to be defined only, not assigned values.

int type constant

When the function returns, if the data returned by the int type is not a real practical data value (for example, a height, width, or size equivalent), only represents the function execution success, failure, the state value of the exception, and these values are a limited number of values, you must use the static constant description of these values, or use enumerations, for example:
int getjsonstring ()
The function returns 1 for the parse JSON data exception, 0 for success, 1 for network connection exception, and 2 for the data portion of the JSON content to be empty. So do not use these literals directly in the code inside the function, these literals are meaningless to the programmer and the code is poorly readable, suggesting the following pattern:
public static final int result_parse_json_exception =-1;
public static final int result_success = 0;
public static final int result_network_exception = 1;
public static final int result_no_data = 2;
The advantage of using these symbolic constant values instead of literals is that the symbolic constant value is made up of uppercase English words, which makes sense and helps programmers to better understand the meaning of the function return value, and the specific assignment value corresponding to the symbolic constant value is easily modified at a later stage.

Activity acceptance parameters and modularity

If an activity can be opened in multiple places, or a fragment may be used in multiple places. When designing the activity and the fragment, we must consider the low coupling, provide the unified parameter interface externally, the process of initiating activity is encapsulated in the static member method of the activity class, similar to the following:

Class MyActivity extends activity{...public static void startactivity (Context context,params param) {Intent Intent = new in Tent (context, Myactivity.class), Intent.putextra ("param", param); startactivity (intent);} public static void Startactivityforresult (context context,params param) {Intent Intent = new Intent (context, Myactivity.class) Intent.putextra ("param", param); Startactivityforresult (Intent,request_code);}}

The transfer of parameters is best encapsulated in a model entity class, avoiding the use of map as a way of parameter passing. It is recommended that the entity class be implemented as a static serializable inner class for the corresponding activity.

Androidstudio Engineering Catalogue Organization

The package structure of the project in Androidstudio should be organized according to the function of each part of the project.

Package of Handler

Each activity will almost define a handler inner class, but many of the activity's handler use duplicate message types, which have redundant code, so you should use these activity to the handler class's message part , extracted into a common handler class. It then uses the inheritance method in each activity to provide the handler class implementation of the activity-specific handler message type.

In addition, the handler sends the message should use the handler class's member function, should not directly use handler.obtainMessage(xxx).sendToTarget(); this kind of primitive sends the message the way, this does not favor reduces the coupling, this kind of detail should hide in the handler inside. The message type of handler should be defined as a static constant inside the handler class, and the constant should not be public and not visible to the outside. This means that the details of sending messages using the handler object should not be exposed to the outside.

Data Update for List

Encapsulates data updates for a ListView and updates data in handlermessage to avoid java.lang.IllegalStateException problems

Transfer parameters between activity and fragment

The data transfer of activity and fragment takes the form of interface, which reduces coupling and facilitates the reuse of fragment:

Modularity of Network request data

Generally in activity we obtain data through the interface of the network request server, this process is usually done in a thread, after obtaining the data, and then through the activity of the handler send a message to notify the activity update data. The thread class that is responsible for fetching the data is generally implemented as an inner class of activity that can directly access the activity's member variables, such as handler, data list objects, and so on. However, this is detrimental to the data fetch thread reuse. If the other activity also needs to obtain the same data, then this function is not reusable, so this is responsible for the data request of the thread class, should not be closely related to the specific handler and activity. should be defined as a static class, handler should be passed in as a parameter instead of directly accessing the member variables of the external class.

Package log function

The log function should be encapsulated as the tag parameter that automatically turns the class name of the current class into the log output, preferably the published app is able to cycle through the log file to the system store, and the log file should be reused in a repeated overlay manner. The following is just an imperfect example:

public class MyLog {public  static final String TAG = "MyApp";  public static void V (Object o,string message)  {      log.v (Tag+o.getclass (). Getsimplename (), message);}  }

Use

MYLOG.V (this, "Hello log");

Print results

V/myapp Mainactivity:hello Log
Version control

With automated versioning, the version number is automatically generated to keep the version of the application consistent with the repository. Use HG to replace the Build.gradle file in the app directory under the project directory, if Manifest also has a version number set, Androidstudio or Build.gradle. You should not manually modify the version number in Androidstudio's project settings at each release.

To add a global exception capture to a program

Should add a global exception capture for the app, there will always be some of our uncaught exceptions, once the user encounters such an exception, the program crashes, we should detect the class of uncaught exception information, the program crashes by writing a file log, or send a message to obtain the exception information, To resolve the bug.

I summarize the Android programming 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.