Replacing findViewById with annotations in Android

Source: Internet
Author: User

 

This article mainly explains how to implement the findViewById function by annotations. First, let's get familiar with how to define an annotation and parse an annotation in java.

The annotation concept was proposed in JDK. Three annotations have been defined in the java. lang Package: Override, Deprecated, SuppressWarnings
Override I believe everyone is very familiar with it. It indicates that this method is used to rewrite the parent class method.
Deprecated indicates that this method or attribute is not recommended in the new jdk version.
SuppressWarning is to block some warnings.

After understanding the annotation concept, we will customize the annotation.

The annotation definition is very similar to the interface, with an additional @

 

public @interface TestPerson{}

Never get rid of the previous @ symbol. If you get rid of it, it becomes the interface definition. The above is the definition of the simplest annotation. Of course, the annotation can also define attributes like the class, as follows:

 

 

Public @ interface TestPerson {// name is both an attribute of this annotation and an annotation method. The value returned by calling name () is name String name () default gavin ;}

I want to define two annotations. One annotation is used to describe the meaning of a class, and the other annotation is used to describe who tests a method in the class to facilitate accountability. The definition is as follows:

 

 

// Public @ interface ClassFunction {String value () default;} used to mark what a class is used ;} // It is used to indicate who tested the method in the class. public @ interface TestPerson {// name is the property rather than the method, and gavin is its default value, you do not need to specify the default value String name () default gavin ;}

So how can I limit whether an annotation is used in a class or in a method? For example, Override is used for method annotation. Deprecated can be used for both methods and classes. Let's take a look at how Override is implemented.

 

 

 

@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}@Documented@Retention(RetentionPolicy.RUNTIME)@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})public @interface Deprecated {}

We found that these two annotations use other annotations in the definition process. annotations such as Target and Retention are called meta annotations. Let's take a look at their meanings.
The function of the Target annotation is to indicate where your annotation is used, and its value is an enumeration type.
1. CONSTRUCTOR: used to describe the CONSTRUCTOR
2. FIELD: used to describe the domain
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


The Retention annotation function shows the lifecycle of your annotation, that is, when it expires. Its value is as follows:
1. SOURCE: valid in the SOURCE file (that is, the SOURCE file is retained)
2. CLASS: valid in the class file (that is, the class is retained)
3. RUNTIME: valid during RUNTIME (that is, reserved during RUNTIME)


Let me introduce these two yuan annotations. Others do not use much. If you are interested, you can Google them yourself.

 

So let's improve our own annotations.

 

 

@ Target (ElementType. METHOD) // act on the METHOD @ Retention (RetentionPolicy. RUNTIME) // valid during RUNTIME (that is, reserved during RUNTIME) public @ interface TestPerson {// name is an attribute rather than a method, and gavin is its default value, you do not need to specify the default value String name () default gavin;} @ Target (ElementType. TYPE) // act on the class @ Retention (RetentionPolicy. RUNTIME) // valid during RUNTIME (that is, reserved during RUNTIME) public @ interface ClassFunction {String value () default ;}

So let's use our annotations.

 

 

@ ClassFunction (used to describe a Person's basic information) public class Person {private static final String TAG = Person; @ TestPerson (name = jj) public void setName (){}}

It should be noted that: if a annotation attribute uses value as the name such as value in ClassFunction, you can directly @ ClassFunction (used to describe the basic information of a person) when assigning values ), however, if you are using another name, you must @ TestPerson (name = jj) to call

The above is the process of defining an annotation. Next we will parse an annotation
Define a TestPerson Annotation

 

 

/*** Com. annotation. testPerson * @ author yuanzeyao * create at 1:30:14, January 1, May 21, 2014 */@ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) public @ interface TestPerson {String name ();}

Then add the annotation to the Person class.

 

 

public class Person {  private static final String TAG = Person;  @TestPerson(name=gavin)  public void getName()  {      }}

Parse Annotation

 

 

Public class Main {private static final String TAG = Main; public static void main (String [] args) {Person person Person = new Person (); // obtain the Class corresponding to Person
 
  
Clazz = Person. class; try {// find the getName Method method = clazz. getMethod (getName, null); // determines whether the request is marked by TestPerson if (method. isAnnotationPresent (TestPerson. class) {// call the getName method. invoke (person, null); // obtain the instance TestPerson test = method annotated by TestPerson. getAnnotation (TestPerson. class); // obtain the name attribute String name = test. name (); System. out. println (this method is test by --> + name) ;}} catch (SecurityException e) {}catch (NoSuchMethodException e) {} catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} catch (InvocationTargetException e ){}}}
 

The definition annotation and resolution annotation have been explained. The following describes how to use annotation in Android to replace findViewById.
Define An Annotation

 

 

@ Target (ElementType. FIELD) @ Retention (RetentionPolicy. RUNTIME) public @ interface InjectView {// id is the Control id. Use the annotation to mark its id int id () default-1;} on a control ;}

Add annotation to Activity

 

 

Public class MainActivity extends Activity {public static final String TAG = MainActivity; // The id @ InjectView (id = R. id. TV _img) private TextView mText; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); try {autoInjectAllField (this);} catch (IllegalAccessException e) {} catch (IllegalArgumentException e) {} If (mText! = Null) mText. setText (Hello Gavin);} public void autoInjectAllField (Activity activity) throws IllegalAccessException, IllegalArgumentException {// obtain the Class clazz = this for the Activity. getClass (); // obtain all fields of the Activity. Field [] fields = clazz. getDeclaredFields (); Log. v (TAG, fields size --> + fields. length); for (Field field: fields) {// determines whether the field is labeled InjectView if (Field. isAnnotationPresent (InjectView. class) {Log. v (TAG, is injectView); // If marked, obtain its id InjectView inject = field. getAnnotation (InjectView. class); int id = inject. id (); Log. v (TAG, id ---> + id); if (id> 0) {// specifies the field to be added when the private member is accessed through reflection. setAccessible (true); // then copy the field to this attribute. set (activity, activity. findViewById (id ));}}}}}

Okay. Write it here. Leave a message to discuss it.

 

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.