Android annotation Usage Details, android Usage Details

Source: Internet
Author: User

Android annotation usage (image and text) and android usage

While using the SSH framework of Java, I have been lamenting that annotations are really convenient. For the principles of annotations, you can refer to my other article Java annotations for details. I have recently studied the use of android annotations. I would like to share with you today.

Android uses the open-source framework androidannotations on GitHub ,. This open-source framework should be the most widely used android annotation framework, mainly because it has many annotation labels designed to meet most of our daily development needs. Androidannotations packs many methods that can be extracted into annotation labels for our use. I will give you a detailed demonstration later.
Let's take a look at how to use this stuff.

Step 1

Download androidannotations
After downloading and decompressing the file, we will see two jar packages:

Step 2

Configure the framework on eclipse:
1. Create an android project, copy the androidannotations-api-3.2.jar to the libs folder, and create a new folder in the project, called compile-lib, copy the androidannotations-3.2.jar file in.

2. select a project, right-click, and select Properties. On the left of the new window, you can see Java Compiler, select Annotation Processin under Java Compiler, and select Enable project specific Settings on the right, special settings are allowed for the project.

3. Expand Annotation Processin, select Factory Path, click Enable project specific Settings on the right, and click Add JARs to Add the jar package.

4. Select the jar package in the new folder and click OK,

Now, the configuration in our development environment is complete.

Step 3

Test whether the configuration is successful
Enter @ E on an Activity to see what the prompt is:
If you see @ EActivity, congratulations, the configuration is successful. If not, check the preceding steps.

Step 4

After configuration, let's see how to use androidannotations.
1. Use of Activity Annotation
To modify the activity configuration in the configuration file, add _:

        <activity            android:name=".MainActivity_"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>

As to why we should change MainActivity to MainActivity _, I will explain it later. Then add the Annotation on MainActivity:

@EActivity(R.layout.activity_main)public class MainActivity extends Activity {


    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);    }

For convenience, add some controls to the main layout file:

<LinearLayout xmlns: android = "" xmlns: tools = "" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" android: orientation = "vertical" tools: context = "com. example. androidannotations. mainActivity "> <TextView android: id =" @ + id/textView1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: text = "@ string/hello_world"/> <Button android: id = "@ + id/button1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Button1"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Button2"/> <Button android: id = "@ + id/button3" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Button3"/> <Button android: id = "@ + id/button4" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Button4"/> <Button android: id = "@ + id/button5" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Go TO Next Activity"/> <Button android: id = "@ + id/button6" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "multi-thread event"/> <TextView android: id = "@ + id/textView2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "TextView"/> <TextView android: id = "@ + id/textView3" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "TextView"/> <TextView android: id = "@ + id/textView4" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "TextView"/> </LinearLayout>

In this case, run the following command to check whether the system reports an error if no layout is set for the Activity:

No crash. All content is displayed normally.@EActivity(R.layout.activity_main)ReplacedsetContentView(R.layout.activity_main);.
Next, we will introduce an annotation related to Activity. During Activity usage, we often need to customize the title bar to hide the default title bar of the system. How can we achieve this:

@WindowFeature({ Window.FEATURE_NO_TITLE , Window.FEATURE_INDETERMINATE_PROGRESS})@EActivity(R.layout.activity_main)public class MainActivity extends Activity {


It is easier to hide the title bar than to hide other titles.

2. instantiate the control Annotation

The instantiated control annotation is another very useful annotation in androidannotations. It also solves one of the most boring tasks in our development process. Normally, we need to use findViewById to instantiate a control, after getting the control, we can convert it to the type we need. The code is large and boring. What are the surprises of androidannotations?

There are a total of four textviews on the main layout file. I use the following three methods for instantiation:

    @ViewById(    TextView tv1;    @ViewById    TextView textView2;    @ViewsById({,})    List<TextView> list;

First:@ViewById( is a very standard way of writing. After a control is declared, the @ ViewById annotation is used to describe the id of the control in the annotation, which is equivalent to replacing such a line of code:

TextView tv1 = (TextView) this.findViewById(;

Second: I did not specify the id used for this annotation label. How is it instantiated? If not specified, androidannotations uses the control name as the id. My second control name is textView2, which is the same as the layout id in xml, therefore, you do not need to specify the id in the annotation.
Third: To declare multiple controls, you can put these controls into a List set and specify multiple IDs in the annotations.

After the control is instantiated, you can assign a value to the control as follows:

    @AfterViews    public void initTextView(){        tv1.setText("hello world!");        textView2.setText("hello android annotations!");        for(TextView tv:list){            tv.setText("hello lenve!");        }    }

This method will be executed after the instance finishes the control.

3. Event Annotation
The many events androidannotations used in our development provide us with annotations:

    @TextChange    @AfterTextChange    @BeforeTextChange    @EditorAction    @FocusChange    @CheckedChange    @Touch    @Click    @LongClick    @ItemClick    @ItemLongClick    @ItemSelect    @OptionsItem    @SeekBarProgressChange    @SeekBarTouchStart    @SeekBarTouchStop

I would like to pick a simple one here. It is also the most commonly used one:

    @Click({,,})    public void btn_click(View v){        switch (v.getId()) {        case            Toast.makeText(this,"btn1", Toast.LENGTH_LONG).show();            break;        case            Toast.makeText(this,"btn2", Toast.LENGTH_LONG).show();            break;        case            Toast.makeText(this,"btn3", Toast.LENGTH_LONG).show();            break;        }    }    @Click(    public void btn4_click(){        Toast.makeText(this,"btn4", Toast.LENGTH_LONG).show();    }

Add the @ Click Annotation on the method to specify the Click Event of the control in the annotation. If it is a Click event of multiple events, it indicates multiple IDs. Use the @ Click annotation in the method.v.getId()Method. If you only set click events for one control, see the button4 example.

The event annotation is actually relatively simple and I will not talk about it much. If you are interested, please refer to the official documentation.

4. Thread Annotation

This is probably the most exciting annotation. Here we will introduce two Annotations:


Undoubtedly, @ Background is used to run the method in the Child thread, while @ UiThreaad is used to run the method in the UI thread.
To achieve a simple effect, click a button and let a TextView automatically update the value.

    @Background    public void doInBackground(){        try {            for (int i = 0; i < 100; i++) {                tvShowNumber(i);                Thread.sleep(1000);            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }    @UiThread    public void tvShowNumber(int i) {        list.get(1).setText(i+"");    }

First, run tvShowNumber (I) Every one second in the doInBackground method. If this method runs in the main thread, it will cause ANR exceptions, so it must be run in the Child thread, however, in android, the UI thread cannot be updated in the Child thread. Therefore, we need to add the @ UiThread tag to the tvShowNumber method, indicating that the method runs in the UI thread.
Let's see:

The annoying Message and Handler are completely discarded here (applause should be noted here ).

5. Upload value annotations between activities
Data transmission is often required for Inter-Activity jump. In a new Activity, you need to use Bundle to obtain the data and determine whether the data is empty. This is very troublesome, let's see how androidannotations solves this problem:
Create a new SecondActivity. Make sure to modify the configuration file by adding _:

        <activity            android:name=".SecondActivity_"            android:label="@string/title_activity_second" >        </activity>

SecondActivity receives two parameters from MainActivity: name and address. Let's take a look at the code in MainActivity:

@ Click (R. id. button5) public void go2NextActivity () {// note that Intent intent = new Intent (this, SecondActivity _. class); intent. putExtra ("name", "zhangsan"); intent. putExtra ("address", "Xi'an"); startActivity (intent );}

Obtain the value from MainActivity in SecondActivity:

    @Extra("name")    String username;    @Extra    String address;

Same as above, if the parameter name is the same, you do not need to describe the parameter name in the annotation; otherwise, you need to specify the parameter name. In this way, the value in MainActivity is automatically obtained. If the value in MainActivity is null, no error is reported. The system automatically handles the exception.

6. Resource file Annotation
You can also use annotations to use resource files. For example, add a string to strings. xml:

<string name="welcome">hello China,Hello xi\'an and guangzhou</string>

In the program, we need to reference this value:

@StringRes(R.string.welcome)    String welcome;

In this way, welcome automatically obtains the value here. Note:@StringResThe imported package isimport org.androidannotations.annotations.res.StringRes;It's not an android package. Don't be fooled.


7. Reasons for adding _
Finally, we can solve another problem, that is, adding _ in the configuration file. To answer this question, please select the project and right-click it to cancel a point before apt_generated.

After cancellation, a folder is added to our project:

The Activity in the folder is the Activity we just created, but it all has an extra underline. Let's open these activities and see:

We wrote the layout file through annotation, which is generated for us again here. So, we finally use the file here during compilation, this is why the configuration file is underlined.

Note: Do not use the private modifier for any code that uses annotations. You can use protected for modification at most, because androidannotations generates the real source code using annotations, if our stuff is modified by private, it won't be able to call these things, so it can only be modified by protected at most.

For more instructions on androidannotations, refer to the official documentation.

Now, we will introduce you to the use of Androidannotations. Please leave a message if you have any questions. Download the source code of this project.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger. I am very grateful if you have any mistakes.

Related Article

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: 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.