Getting Started with android-annotations

Source: Internet
Author: User
Tags xml example

Reprint please indicate source: http://blog.csdn.net/goldenfish1919/article/details/41577217

Androidannotation is a very good frame (Https://github.com/excilys/androidannotations/wiki) that can be done: Dependency Injection (Dependency injection) , a simplified threading model (simplified threading model), event binding, and REST Client.

Very useful, and more importantly, it has no impact on performance! In this article we take a brief look at some of the things to get started.
1. Start with the example (refer to https://github.com/excilys/androidannotations/wiki/FirstActivity):
Androidmanifest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.hello "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <application android:allowbackup= "Tru"            E "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "> <activity Android:name= "Com.example.hello.MainActivity_" android:label= "@string/app_name" > <intent-filt er> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity an Droid:name= "Com.example.hello.SecondActivity_"/> </application></manifest>
It defines two activity, with an underscore followed by the name.

2.mainactivity.java: Note that the name here is not underlined
@EActivity (r.layout.activity_main) public class Mainactivity extends activity {@ViewById (r.id.myinput) EditText Myinput; @ViewById (R.id.mytextview) TextView TextView; @ViewById (r.id.mybutton2) Button btn2; @StringRes (r.string.go_ To_second) String btn2txt, @AfterViewsprotected void Afterviews () {btn2.settext (btn2txt);} @Clickvoid MyButton () {String name = Myinput.gettext (). toString (); Textview.settext ("Hello" + name);} @Clickvoid MyButton2 () {secondactivity_.intent (this). Start ();}} Activity_main.xml<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:/ /schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orie         ntation= "vertical" > <edittext android:id= "@+id/myinput" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content"/> <button android:id= "@+id/mybutton" Android:layout_wid Th= "Fill_parent" android:layout_height="Wrap_content" android:text= "click me!"/> <textview android:id= "@+id/mytextview" Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content"/> <button android: Id= "@+id/mybutton2" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android : text= "@string/go_to_second"/> </LinearLayout>
Secondactivity the source code will not post.

After using injection, the code seems to be very concise and there is no such thing as a bunch of findviewbyid.

How to compile and run it (refer to https://github.com/excilys/androidannotations/wiki/CustomizeAnnotationProcessing):
(1) If you are using Javac, you need to pass-aandroidmanifestfile=/path/to/androidmanifest.xml This parameter to indicate the manifest file.
(2) If you are using Eclipse, right-click on the project->properties->java compiler->annotation processing->enable Annotation Processing,
Then add the Androidannotations jar package to the factory path.
(3) If you are using version 3.1 of Maven,maven-compiler-plugin, you can set compilation parameters.
<plugin>    <artifactId>maven-compiler-plugin</artifactId>    <version>3.1</ version>    <configuration>        <encoding>UTF-8</encoding>        <source>1.6</ source>        <target>1.6</target>        <compilerArgs>            <arg>-atrace=true</arg >            <arg>-AlogLevel=trace</arg>            <arg>-AlogConsoleAppender=true</arg>   <arg>-AandroidManifestFile=/path/to/AndroidManifest.xml</arg>        </compilerArgs>    < /configuration></plugin>
All of the available parameters are as follows:
Trace:boolean, which is used to enable or disable @trace annotations, which are executed by logging the method via log.
Androidmanifestfile:string, by default, Androidannotations will find androidmanifest.xml recursively in its parent folder, if your project has a special structure that you can specify with this.
Resourcepackagename:string, by default, Androidannotations will extract the application's package from the Androidmanifest.xml file to find the R file, which can be set if the R file is in a customised package.
Logfile:string, starting from 3.0, Androidannotations uses a custom logger to record the log during code execution. The log is written by default in the {Outputfolder}/androidannotations.log file.
The {outputfolder} parameter looks for the root project folder,:target-> build, Bin, in the following order. If {OutputFolder} is not found, you can use logfile to specify the output file. {OutputFolder} can use placeholders to dynamically change file names.
Loglevel:string,enum (Trace, debug, info, warn, error): The default logging level is debug and changing to trace may be useful.
Logappenderconsole:boolean, by default, Androidannotations uses Fileappender and MessagerAppender2 log Appender, The Fileappender is written in the log file and Messagerappender is displayed in the IDE's message list. You can set Logappenderconsole to true to enable another consoleappender.
Threadcontrol:boolean, which is used to enable or disable @supposeuithread and @supposebackground annotations, by default is true, which guarantees that the method is called in the correct thread.

3. Impact on performance
No Impact! Because its principle is to generate subclasses of the activity class, not using reflection! We can look at the activity that the compiler helped us generate automatically:
Public final class Mainactivity_ extends mainactivity{@Override public void onCreate (Bundle savedinstancestate) {        Init_ (savedinstancestate);//This will handle @stringres, @ColorRes et cetera super.oncreate (savedinstancestate); Setcontentview (Layout.activity_main);//here corresponds to @eactivity (r.layout.activity_main)} private void Init_ (Bundle savedinst        Ancestate) {Resources Resources_ = this.getresources ();    Btn2txt = resources_.getstring (String.go_to_second);        } @Override public void Setcontentview (int layoutresid) {Super.setcontentview (LAYOUTRESID);    Aftersetcontentview_ ();        } @Override public void Setcontentview (view view, Layoutparams params) {Super.setcontentview (view, params);    Aftersetcontentview_ ();        } @Override public void Setcontentview (view view) {Super.setcontentview (view);    Aftersetcontentview_ (); } private void Aftersetcontentview_ () {//@ViewById TextView = ((TextView) findviewbyiD (Id.mytextview));        Myinput = ((EditText) Findviewbyid (id.myinput));            BTN2 = (Button) Findviewbyid (id.mybutton2);//@Click {View view = Findviewbyid (Id.mybutton2);                    if (view!= null) {View.setonclicklistener (new Onclicklistener () {@Override                    public void OnClick (view view) {MainActivity_.this.myButton2 ();            }                }                );            }}//@Click {view view = Findviewbyid (Id.mybutton);                    if (view!= null) {View.setonclicklistener (new Onclicklistener () {@Override                    public void OnClick (view view) {MainActivity_.this.myButton ();            }                }                ); }} afterviews ();//This invokes the Afterviews () method of the @afterviews callout} public static mainactivity_. Intentbuilder_ Intent (Context Context) {return new mainactivity_.    Intentbuilder_ (context);        } public static class Intentbuilder_ {//This is the private Context context_ for StartActivity and Startactivityforresult;        Private final Intent Intent_;            Public Intentbuilder_ (Context context) {Context_ = context;        Intent_ = new Intent (context, mainactivity_.class);        } public Intent get () {return intent_; } public mainactivity_.            INTENTBUILDER_ flags (int flags) {intent_.setflags (flags);        return this;        } public void Start () {context_.startactivity (INTENT_); } public void Startforresult (int requestcode) {if (context_ instanceof Activity) {(Act            ivity) context_). Startactivityforresult (Intent_, Requestcode);            } else {context_.startactivity (INTENT_); }        }    }}

Finally, take a look at the complete Pom.xml example (https://github.com/excilys/androidannotations/blob/develop/examples/maveneclipse/pom.xml):

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/maven-v4_0_0.xsd "><modelVersion>4.0.0</modelVersion><groupId> Org.androidannotations</groupid><artifactid>maveneclipse</artifactid><version>0.0.1- snapshot</version><packaging>apk</packaging><name>maveneclipse</name>< properties><project.build.sourceencoding>utf-8</project.build.sourceencoding>< android.version>4.1.1.4</android.version><android.platform>16</android.platform>< Androidannotations.version>3.2</androidannotations.version><java.version>1.6</java.version ></properties><dependencies><dependency><groupId>com.google.android</groupId> <artifactid>android</artifactid><version>${android.version}</version><scope>provided</scope></dependency><dependency> <groupId>org.androidannotations</groupId><artifactId>androidannotations</artifactId> <version>${androidannotations.version}</version><scope>provided</scope></dependency ><dependency><groupId>org.androidannotations</groupId><artifactId> androidannotations-api</artifactid><version>${androidannotations.version}</version></ Dependency></dependencies><build><plugins><plugin><artifactid> maven-compiler-plugin</artifactid><version>3.1</version><configuration><source>$ {java.version}</source><target>${java.version}</target><compilerargs><arg>- Aloglevel=trace</arg></compilerargs></configuration></plugin><plugin><groupid >com.jayway.maven.plugins.android.generation2</groupid><artifactid>android-maven-plugin</artifactid><version>3.9.0-rc.3</version>< configuration><sdk><platform>${android.platform}</platform></sdk>< undeploybeforedeploy>true</undeploybeforedeploy></configuration><extensions>true</ Extensions></plugin></plugins></build></project>


Getting Started with android-annotations

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.