Android annotation applications and principles

Source: Internet
Author: User

Android annotation applications and principles
Before this article, you must first have a basic understanding of the java annotation section (not too in-depth ). To put it simply, the annotation is used to help us develop java code, and the annotation itself cannot interfere with java source code execution. In android, annotations are mainly used to do such a few things: 1. Along with the compiler, you will be given some warning information. 2. With some ides, you can write java code more conveniently, quickly, securely, and effectively. Google's support-annotations library focuses on this. 3. Some spring-configurable functions are provided along with reflection, which is convenient and concise (this part can be skipped if it has j2ee development experience ). First, let's take a look at the official library. Add compile 'com. android. support: support-annotations: 22.2.0 'note that I have obtained the version of version22.2. If there is an update during your reference, android studio may prompt you that sync fails, at this time, you need to go to the Google official website to check the latest version number and replace it yourself. Then we can see what functions this Google annotation Library provides for us. First, let's take a look at the Nullness annotation. There are two main types: @ Nullable and @ NonNull. The former indicates that it can be empty. The latter indicates that it cannot be empty. I will only demonstrate the latter (the former can be tested by myself) to define a function and then let's call it. 1 String a = null; 2 sayHello (a); at this time, the IDE will automatically give us a warning (in fact, most of the warning information of the ide is also from the compiler)

1 Argument 'a' might be null less... (Ctrl+F1) 2 This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.3 Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException errors.4 More complex contracts can be defined using @Contract annotation, for example:5 @Contract("_, null -> null") — method returns null if its second argument is null @Contract("_, null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it 6 The inspection can be configured to use custom @Nullable7 @NotNull annotations (by default the ones from annotations.jar will be used)

 

Introduce Resource Type Annotations to define a method 1 private String sayHello (@ StringRes int resId) {2 return "; 3} and then call 1 sayHello (R. layout. activity_main); in this place, this annotation means that you can only pass the string type id, and we pass the layout type, if you do not add that annotation, the ide and the compiler will not respond, and errors will occur at runtime. But after you add it, you will find that the IDE also reports an error directly! Another example is this code.
 1  class TestAnoataion { 2  3         public void testAnoation() { 4             Log.v("main", "test anoation"); 5         } 6     } 7  8     class TestAnoataion2 extends TestAnoataion 9     {10         public void testAnoation()11         {12 13         }14     }

 

If the design of the parent class is intended, if you want to override the testAnoation method, you must call the testAnation method of the parent class. Just like the oncreate method of our activity. If the subclass is not written as super. testAnoation, you will easily report an error if you do not know it. However, if you add annotations. Then the ide will clearly prompt you whether the error is very powerful? After you call the super statement, everything will be harmonious! This support library will be introduced here for the time being. I personally suggest you go through an official document by yourself if you have time. The annotations defined here are very helpful for improving the code quality. Be sure to master and learn. Finally, let's look at a small example. Many android Developers prefer to bind your Control id to some open-source libraries that rely on injection. This method is not only elegant but also easy to use. Butterknife, an open-source library, must have been used by many people. I wrote a demo to demonstrate the principles of these libraries. It is actually quite simple. It should be noted that to understand this small demo, you need to have basic reflection knowledge in addition to basic annotation knowledge. On reflection I also wrote a long time ago a tutorial http://www.cnblogs.com/punkisnotdead/p/3384464.html won't be able to hurry up to make up. First define an InjectView Annotation
1 package com. example. administrator. testfab; 2 3 import java. lang. annotation. elementType; 4 import java. lang. annotation. retention; 5 import java. lang. annotation. retentionPolicy; 6 import java. lang. annotation. target; 7 8/** 9 * Created by Administrator on 2015/8/5. 10 */11 12 @ Target (ElementType. FIELD) 13 @ Retention (RetentionPolicy. RUNTIME) 14 public @ interface InjectView {15 // id indicates which controls, and-1 indicates that the default value 16 int id () default-1; 17} is not obtained}

 

Then define an interpreter
 1 package com.example.administrator.testfab; 2  3 import android.app.Activity; 4 import android.view.View; 5  6 import java.lang.reflect.Field; 7  8 /** 9  * Created by Administrator on 2015/8/5.10  */11 public class InjectViewParser {12 13     public static void inject(Object object) {14 15         try {16             parse(object);17         } catch (Exception e) {18             e.printStackTrace();19         }20     }21 22     public static void parse(Object object) throws Exception {23         final Class<?> clazz = object.getClass();24         View view = null;25         Field[] fields = clazz.getDeclaredFields();26         for (Field field : fields) {27             if (field.isAnnotationPresent(InjectView.class)) {28                 InjectView injectView = field.getAnnotation(InjectView.class);29                 int id = injectView.id();30                 if (id < 0) {31                     throw new Exception("id must not be null");32                 } else {33                     field.setAccessible(true);34                     if (object instanceof View) {35                         view = ((View) object).findViewById(id);36                     } else if (object instanceof Activity) {37                         view = ((Activity) object).findViewById(id);38                     }39                     field.set(object, view);40                 }41 42             }43 44         }45 46     }47 } 

 

Finally, you can use it in actity.
1 package com. example. administrator. testfab; 2 3 import android. OS. asyncTask; 4 import android. OS. bundle; 5 import android. support. annotation. callSuper; 6 import android. support. annotation. nonNull; 7 import android. support. annotation. nullable; 8 import android. support. annotation. stringRes; 9 import android. support. v7.app. appCompatActivity; 10 import android. util. log; 11 import android. view. menu; 12 im Port android. view. menuItem; 13 import android. widget. button; 14 15 public class MainActivity extends AppCompatActivity {16 17 @ InjectView (id = R. id. bt) 18 private Button bt; 19 20 21 @ Override22 protected void onCreate (Bundle savedInstanceState) {23 super. onCreate (savedInstanceState); 24 setContentView (R. layout. activity_main); 25 // start to inject 26 InjectViewParser. inject (this); 27 // this is mainly because if the test injection id is successful, no error will be reported ~ 28 bt. setText ("inject done"); 29 30 31} 32 33 34 @ Override35 public boolean onCreateOptionsMenu (Menu menu) {36 // Inflate the menu; this adds items to the action bar if it is present.37 getMenuInflater (). inflate (R. menu. menu_main, menu); 38 return true; 39} 40 41 @ Override42 public boolean onOptionsItemSelected (MenuItem item) {43 // Handle action bar item clicks here. the action bar will44 // automatically handle clicks on the Home/Up button, so long45 // as you specify a parent activity in AndroidManifest. xml.46 int id = item. getItemId (); 47 48 // noinspection SimplifiableIfStatement49 if (id = R. id. action_settings) {50 return true; 51} 52 53 return super. onOptionsItemSelected (item); 54} 55 56 57 58}

 

 

 

 

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.