"Turn" in layman's Android support Annotation

Source: Internet
Author: User

"Turn from"http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0427/2797.html

English Link: http://anupcowkur.com/posts/a-look-at-android-support-annotations/

Translation links in layman's Android support Annotations

Introduction: If you have encountered before the method parameters in the case of @nonnull and do not know what it is doing, this article will answer your questions.

The original text reads as follows:

In the Android support Library19.1 release, the Android tools team introduced several cool annotation types for developers to use in the project. The support library itself also uses these annotations, which is a good omen. Let's take a good look at it. These annotations can be easily added to our project by Gradle:

Compile ' com.android.support:support-annotations:20.0.0 '

There are three types of annotations available for us to use:

    • nullness annotations;

    • resource type annotations;

    • Intdef and stringdef annotations;

We will use code examples to explain the role of each type and how they are used in engineering.

nullness Annotations

Parameters decorated with @nonnull annotations cannot be null. In the following code example, we have a null name variable that is passed as a parameter to the SayHello function, which requires that the parameter be a non-null string type:

  Class  mainactivity extends   actionbaractivity {@Override  protected   void   OnCreate (Bundle savedinstancestate) { super  .oncreate (Savedinstancestate);         Setcontentview (R.layout.activity_main);         String name  = null  ;    SayHello (name);         void   SayHello (@NonNull String s) { Toast.maketext ( this , "Hello" + S,    Toast.length_long). Show (); } }
 

Because the parameter string s in the code uses the @nonnull annotation decoration, the IDE warns us of a problem with this place in the form of a warning:

If we assign a value to name, such as String name = "US Lord Duarte", then the warning disappears. function parameters that are decorated with @nullable annotations or return values can be null. Assuming that the User class has a variable named name, using User.getname () access, we can write the following code:

 Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);         Setcontentview (R.layout.activity_main); User User=NewUser ("Our Lord Duarte"); Toast.maketext ( This, "Hello" +getName (user), Toast.length_long). Show (); } @Nullable String getName (@NonNull user user) {returnUser.getname (); } }
 

Because the return value of the GetName function is decorated with @nullable, it is called:

Toast.maketext (This, "Hello" + getName (user), Toast.length_long). Show ();

Not checking whether the return value of GetName is empty will likely result in crash.

Resource type Annotations

Have you ever passed the wrong resource integer value to a function, and can you happily get the integer value you want? Resource type annotations can help us achieve this accurately. In the following code, our SayHello function expects to accept the ID of a string type and use the @stringres annotation adornment:

  Class  mainactivity extends   actionbaractivity {@Override  protected   void   OnCreate (Bundle savedinstancestate) { super  .oncreate (Savedinstancestate);         Setcontentview (R.layout.activity_main);    SayHello (R.style.apptheme);  void  SayHello (@StringRes int  Span style= "color: #000000;" > ID) {Toast.maketext ( this , "Hello" + g    Etstring (ID), Toast.length_long). Show (); } }

And we passed a style resource ID to it, and the IDE will prompt the following warning:

Similarly, we put the warning in place using a string resource ID instead of a warning disappears:

SayHello (R.string.name);

Intdef and stringdef annotations

The last type of annotation we want to cover is the IntelliJ-based "magic constant" check mechanism (http://blog.jetbrains.com/idea/2012/02/new-magic-constant-inspection/ (We don't need to know more about how this mechanism is implemented, and you can click on the link if you want to know).

Many times, we use integer constants instead of enumeration types (performance considerations), such as we have a Icecreamflavourmanager class, which has three modes of operation: Vanilla,chocolate and Strawberry. We can define a new annotation named @flavour and use @intdef to specify the type of value it can accept.

 Public classIcecreamflavourmanager {Private intflavour;  Public Static Final intVANILLA = 0;  Public Static Final intChocolate = 1;  Public Static Final intStrawberry = 2; @IntDef ({VANILLA, chocolate, strawberry}) Public@InterfaceFlavour {} @Flavour Public intGetflavour () {returnflavour; }      Public voidSetflavour (@Flavourintflavour) {         This. Flavour =flavour; } }

At this point, if we call Icecreamflavourmanager.setflavour using the wrong integer value, the IDE will make an error as follows:

The IDE will even prompt us to use valid values:

We can also specify an integer value as the flag bit, meaning that these integer values can be manipulated with or, using ' | ' or ' & '. If we define @flavour as the following flag bit:

true, value = {VANILLA, chocolate, strawberry})    public @interface  Flavour {}

Then you can call the following:

Icecreamflavourmanager.setflavour (Icecreamflavourmanager.vanilla & icecreamflavourmanager.chocolate);

@StringDef usage is roughly the same as @intdef, except for string types.

For questions such as what new annotation types will be added in the future, or how these annotations are dependent, and how annotations interact with IntelliJ itself, you can view the URL: http://tools.android.com/tech-docs/support-annotations.

I wrote an example myself:

 Packagecom.kale.lib.utils;ImportAndroid.content.Context;ImportAndroid.os.Looper;ImportAndroid.support.annotation.IntDef;ImportAndroid.support.annotation.NonNull;ImportAndroid.widget.Toast;/** * @authorJack Tony * @date 2015/4/29*/ Public classEasytoast {@IntDef ({toast.length_short, toast.length_long}) Public@InterfaceLength {} Public Static voidMaketext (@NonNull context Context,intmsg)    {Maketext (context,string.valueof (msg)); }         Public Static voidMaketext (@NonNull context context, String msg) {if(Context! =NULL{toast.maketext (context, MSG, toast.length_short). Show (); }    }     Public Static voidMaketext (@NonNull context Context,intMSG, @Lengthintlength)    {Maketext (context,string.valueof (msg), length); }         Public Static voidMaketext (@NonNull context context, String msg, @Lengthintlength) {        if(length = = Toast.length_short | | length = =Toast.length_long) {            if(Context! =NULL{toast.maketext (context, msg, length). Show (); }        }    }     Public Static voidMaketextinthread (@NonNullFinalContext Context,intmsg)    {Maketextinthread (context, string.valueof (msg)); }         Public Static voidMaketextinthread (@NonNull context context, String msg) {Maketextinthread (context, MSG, toast.length_short); }     Public Static voidMaketextinthread (@NonNull context Context,intMSG, @Lengthintlength)    {Maketextinthread (context,string.valueof (msg), length); }         Public Static voidMaketextinthread (@NonNullFinalContext Context,FinalString msg, @LengthFinal intlength) {        NewThread () {@Override Public voidrun () {looper.prepare ();//Remove FirstToast.maketext (context, msg, length). Show (); Looper.loop ();//enter loops in loop to view Message Queuing}}.start (); }}

"Turn" in layman's Android support Annotation

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.