Android Development Learning Path-let annotations help you simplify your code and completely abandon Findviewbyid

Source: Internet
Author: User

This article is mainly to record the use of annotations notes, if there are errors please put forward.

In the usual case, we have a view in the activity, we want to get this instance of the view by Findviewbyid this method, and then this method returns an object type, we also need to make a forced type conversion, but I believe many people have encountered , when there are a lot of controls in one of our layouts, it is very annoying for each control to do the above, especially forced type conversion, even with alt+enter, more than a few times tired. And today is to use annotations to simplify this complex step, after we have written the appropriate code, the method of obtaining an instance becomes as simple as the following

@ViewInject (r.id.buy) Private Button buy;

With these two simple lines of code, we can instantiate the view corresponding to the ID, and let's step-by-step to learn how to use annotations.

First of all, we have to know that in Java, through reflection, we can know the details of each class, such as what field, what method, class name, etc., we use reflection to call the method in the class with the annotation and reflection, and then read the parameters of the annotation to perform the method. To put it simply, we're actually going to call Findviewbyid, but this method can be executed in a tool class, and we just need to give the parameters as above.

First, the reflection, reflection is to allow us to dynamically manipulate a class, get the fields of the class, execute the class method, get the name of the class, and so on, here we generally use the following methods:

GetMethod: Getting the public method in a class

Getdeclaredmethod: Gets all the methods in the class

GetField: Gets the Public field (property) in the class

Getdeclaredfield: Gets all the fields in the class

Please refer to the source code of class for your own reference.

Besides the annotations, the most annotation fetch we see is @override, and when we rewrite the methods in the parent class, the annotations are automatically generated by the compiler, and this annotation simply indicates that the method is overriding the parent class method.

So how do we customize the annotations we want? Actually very simple, look directly at the code:

@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  viewinject{    int  value ();}

@Target means that we annotate the target, here is the Elementtype.field, which is the function of the field

There are several types of ElementType:

1.CONSTRUCTOR: Used to describe the constructor
2.FIELD: Used to describe the field
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

@Retention means the operation level of the annotation

There are several types of retentionpolicy:

1.SOURCE: Valid in source file (i.e., source file retention)
2.CLASS: Valid in class file (that is, class reserved)
3.RUNTIME: Valid at run time (that is, runtime retention)

@interface is to indicate that the class is an annotation, the @ must not be missed, otherwise it becomes an interface.

If you want to know more about annotations, you can refer to: http://www.cnblogs.com/gmq-sh/p/4798194.html this blog post, very detailed, for the function we want, the above content is sufficient

The annotations are defined, and if we use them directly, there is no effect, because the annotations are just a piece of code and are not associated with our controls, so we're going to write a tool class to do the correlation

 Public classAnnotateutils { Public Static voidinjectviews (activity activity) {Class<?extendsActivity> object = Activity.getclass ();//get activity's classfield[] fields = Object.getdeclaredfields ();//get all fields of activity by class         for(Field field:fields) {//Traverse all fields//gets the annotation for the field and returns null if there is no viewinject annotationViewinject viewinject = field.getannotation (viewinject.class); if(Viewinject! =NULL) {                intViewId = Viewinject.value ();//gets the parameter of the field annotation, which is what we pass in the control ID                if(ViewId! =-1) {                    Try {                        //gets the Findviewbyid method in the class with the argument intmethod = Object.getmethod ("Findviewbyid",int.class); //executes the method, returning a view instance of type ObjectObject Resview =Method.invoke (activity, viewId); Field.setaccessible (true); //set the value of the field to an instance of the viewField.set (activity, Resview); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); }                }            }        }    }}

In the tool class, we get the class of activity, we get all the fields in the class, we traverse the fields, if we have viewinject annotations, we get the values in the annotations, we get the instances of the corresponding view by getting and executing the methods in the Class (Findviewbyid). Finally, the instance is assigned to the current field, and the whole process is completed.

When we need to use annotations, we just need to define the view, add the corresponding annotations on the view field, pass in the ID, and invoke the method of the above tool class in the OnCreate method.

  @ViewInject (r.id.buy)  private  Span style= "color: #000000;" > button buy, @ViewInject (R.id.money)  private   TextView money; @ViewInject (r.id.tv_power)  private   TextView Power; @ViewInject (R.id.tv_life)  private   TextView life; @ViewInject (R.id.tv_dex)  private  TextView Dex; 
@Override protected void onCreate (Bundle savedinstancestate) {    super. OnCreate (savedinstancestate);    Setcontentview (r.layout.activity_main);    Annotateutils.injectviews (this);}

Finally, there are a few notes:

① if the values in the annotations are not value, then in the case of annotations it is time to give the name of the corresponding value, if we define the following in the annotations:

@Target (Elementtype.field) @Retention (retentionpolicy.runtime)  public @Interface  viewinject{    int  ID ();}

So in the comments, you need this:

@ViewInject (id = r.id.buy)private Button buy;

Because the name of value is the default, if we define value, then the annotation can be omitted

② annotations can also help us inject layout, set monitoring, etc., if interested, can continue to explore

③ the use of annotations, at the end of the sentence can not add ";"

Android Development Learning Path-let annotations help you simplify your code and completely abandon Findviewbyid

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