Brief introduction
In the previous development, you must have used the xUtils
and ButterKnife
other Dependency injection framework, you can use these frameworks to simplify your code, because many of the code is repetitive, for the old driver, you certainly do not want to waste a lot of time to write some repetitive things, such as findViewById
the Code, So the use of good framework for rapid development is very necessary, today to chat is open source Framework AndroidAnnotations
, first look at the official introduction:
Androidannotations is a Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what ' s really important. By simplifying your code, it facilitates it maintenance.
Fast Android Development. Easy maintainance
Let's translate:
AndroidAnnotations
is an open source framework that lets you develop quickly, and it lets you focus on what's really important, it simplifies your code, and facilitates your later maintenance;
Fast development, simple and easy to maintain
This is AndroidAnnotations
, you can not stop the use of the rapid development of easy-to-maintain open-source framework, OK, following my footsteps, a to uncover its mystery ...
Features and Environment configuration
In the official homepage, given an example, before and after the use of the comparison, we will find that the code is reduced by half, visible its powerful, to first page address: Point me, of course, since it is open source, but also the GitHub project address: Point I
Features of using this framework:
- Dependency Injection (Dependency injection): Support
view
, extras
, system service
, resource
etc.
- Simple threading model (simplified threading models): Make method annotations to let the method execute on the UI thread or background thread
- Event binding: Make method annotations to allow time for the method to execute
view
without adding some listening
- REST client: Create an interface to
AndroidAnnotations
implement the
- No Mystery (no magic):
AndroidAnnotations
at compile time a subclass is generated, and you can look at the code in the subclass to see how it works.
- Compile detection: A variety of annotations are provided to detect possible exceptions during code compilation and to prompt developers for improved code quality
AndroidAnnotations
To achieve these beautiful features, it only takes less than 150kb of size
Environment configuration
In Androidstudio, you only need to build.gradle
add a single line of compilation in:
dependencies { compile ‘com.android.support:support-annotations:23.3.0’}
Of course, if your project has already used the V7 package, it can be used directly, is not very simple ...
Using @nullable and @NonNull
The detection parameter or method return value can be null, which is one of the most common and basic annotations in the framework, using these two annotations, in Android Studio, if the code is unsafe, you will be given a smart hint, we have a sample comparison below:
Parameters decorated with @nonnull annotations cannot be null, in the following example, we have a function that pops up name, which needs to guarantee that the passed-in parameter cannot be null, let's look at the comparison:
Not annotated:
Plus @nonull annotations
We can see the addition of @nonnull annotations, Android Studio will automatically detect unsafe code and give friendly hints, prompting the developer to modify, of course, if we change to @nullable will not appear the hint;
We can also apply @nullable to methods so that the return value of the method is allowed to be null, but may lead to crash in some cases;
@CheckResult
The note is intended to detect if the return value of the method is needed, and if it is not used, the Androidstudio will give a warning, and the following example compares:
Not annotated:
Plus @checkresult annotations
@EActivity, @ViewById, @Click
These three annotations should be the most helpful for our code simplicity.
- @EActivity: You need to follow a layout ID to indicate the XML layout that the activity is loading, so the original OnCreate () method does not have to be written;
- @ViewById: Consistent with Findviewbyid, and the control ID can be not written after @viewbyid, provided that the control variable name is consistent with the control ID
- @Click: That is, the control's click event, and if the control ID is the same as the method name, then the control ID is not written later. The note can be written separately, or it can be combined with multiple buttons
Let's write an activity that uses the Androidannotation framework.
Import Android.support.v7.app.appcompatactivity;import Android.widget.textview;import Android.widget.Toast;import Com.googlecode.androidannotations.annotations.click;import Com.googlecode.androidannotations.annotations.eactivity;import com.googlecode.androidannotations.annotations.viewbyid;//here Add annotations can not write OnCreate method @eactivity (r.layout.activity_test _annotation) public class Testannotation extends Appcompatactivity { @ViewById (r.id.tv_name)//If the variable name and the control ID are the same, There is no need to write ID TextView tv_name; @Click (r.id.showname)//If the control ID is consistent with the method name, you do not have to write the ID public void showname () { Toast.maketext (this,tv_name.gettext (), Toast.length_short). Show (); }}
Let's see how to write if there are multiple click events for a button
@Click ({r.id.bt1,r.id.bt2,r.id.bt3}) void buttonclicked (Button bt) { switch (Bt.getid ()) {case r.id.bt1 : Break ; ... } }
Note: If the control ID is consistent with the variable name and no control ID is written after @viewbyid, it cannot be called directly in the ShowName method when it is used, because a null pointer is reported at run time, so it needs to be used in the Afterview annotation method
@AfterView void init () { tv_name.settext ("Hello"); }
Resource reference type annotations
In our usual development we will often use to refer to some resources, compared to the resources and string resources or color value resources, because these resources are the type of the int value, so sometimes we have to set the string resource for TextView also may reference the image resource ID, will cause problems, For example, the following exception occurs:
android.content.res.resources$notfoundexception:string Resource ID #0x3039
And in the code detection when we are very difficult to find, and now have the resource type annotation, these problems are no longer a problem, we first look at the resource type annotations are mainly:
@StringRes: A resource that indicates that a parameter, variable, or function return value should be a string type
@ColorInt: Indicates that a parameter, variable, or function return value should be a color value instead of a color resource reference, such as an integer value that should be a aarrggbb.
@ColorRes: Indicates that a parameter, variable, or function return value should be a color-type resource, not a colour value. Attention and Colorint Differences
@AnimRes: Indicates that a parameter, variable, or function return value should be a resource of type Anim
@DrawableRes: Indicates that a parameter, variable, or function return value should be a resource of type drawable
@DimenRes: Indicates that a parameter, variable, or function return value should be a resource of type dimension
Let's take a comparison of the code examples below, where we define a method in which only the int reference of the @stringres annotation is accepted
Before the comment is not added:
After adding the annotations:
If we change to r.string.app_name, the hint will automatically disappear:
We can see that Androidstudio has given us hints so that we are no longer afraid of quoting mistakes;
Thread annotations
Thread annotations are primarily used to detect whether a function executes in a thread of a specified type, with four types of annotations;
@UiThread
@MainThread
@WorkerThread
@BinderThread
where @uithread and @MainThread in most of the usage scenarios, is replaceable, if all the methods in a class are executed in the same thread, they can be annotated directly in the class itself;
For the code example, the Asynctask is the most appropriate, but we all know that the doInBackground
method is Workthread and the UI update is not possible, so if the onProgressUpdate
UI is updated outside of the method, the IDE gives us a direct hint:
Value constraint annotations @FloatRange, @IntRange, @Size @floatrange usage
If, in the defined method, the parameter to be passed is a float or double type, and you need to ensure that the value is within a certain range, you can use the @FloatRange annotation, if the setting range is 0.0~1.0, if the value of 12,ide will be directly prompted:
@IntRange usage
Of course, you can also constrain the int value, for example, to 0~255, and if the value is 300, the error message is reported:
These are very useful, because some API limit value is 0~1, some for 0~255, with this annotation limit, you do not have to fear in the code to pass the wrong parameters;
@Size usage
For data, collections and strings we can use @size to limit the usage as follows:
String most commonly: @Size (max=10)
Arrays can have only 2 elements: @Size (2)
The collection cannot be empty and has at least one element: @Size (min=1)
Permission notes: @RequiresPermission
If our method requires some permission, but we do not know whether it is configured in the manifest file, we can use this permission annotation;
Method Required permission annotations
@RequiresPermission (Manifest.permission.WRITE_EXTERNAL_STORAGE) public void Writeinfo (String name) { // TODO what want }
If you need more than one permission, use the AnyOf property:
}
If you need to use multiple permissions, use the AllOf property:
}
Intent permission Annotations
In the case of intent permissions, we can label the permission requirements on the defined intent constants:
@RequiresPermission (Manifest.permission.BLUETOOTH) public static final String Action_view = " Android.bluetooth.adapter.action.REQUEST_DISCOVERABLE ";
Content Provider Permission Annotations
For content providers permissions, you can annotate each permission requirement with @read or @write:
@RequiresPermission. Read (@RequiresPermission (read_history_bookmarks)) @RequiresPermission. Write (@ Requirespermission (Write_history_bookmarks)) public static final Uri Bookmarks_uri = Uri.parse ("content://browser/ Bookmarks ");
Keep permission annotations
It is believed that each of our small packaged partners knows how painful it is to keep a certain method in a class, and you have used a code like this in Proguard:
-keep class Com.foo.bar {public static}
The use of annotations makes it easy to get to the army of these problems, Androidannotations will tell Proguard not to optimize the specified function or class:
@Keeppublic void Setanni (@IntRange (from=0, to=255) int anni) {//todo What do you want}
Note: According to the official documentation, currently this note is not added to the Gradle plugin, we will continue to wait ...
Well, to this we have a certain understanding of the Androidannotatios open-source framework, the following to enjoy the use of it, these are only part of the framework, more fun and interesting features to wait for our own to explore, I hope we all have a good day, life is not easy, we must cherish ...
Androidannotations Framework Detailed