android-annotations使用入門

來源:互聯網
上載者:User

標籤:android   blog   http   io   ar   color   os   使用   sp   

轉載請標明出處:http://blog.csdn.net/goldenfish1919/article/details/41577217

androidannotation是一個非常牛逼的架構(https://github.com/excilys/androidannotations/wiki),可以做到:依賴注入(Dependency Injection),簡化的執行緒模式(Simplified  threading model),事件綁定(Event binding),REST Client。

非常好用,更重要的是它對效能無影響!本文我們簡要的來看一下一些入門的東西。
1.從例子開始(參考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="14"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name">        <activity            android:name="com.example.hello.MainActivity_"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name="com.example.hello.SecondActivity_" />    </application></manifest>
裡面定義了兩個activity,注意名字後面都帶了一個底線。

2.MainActivity.java:注意這裡的名字沒有底線
@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:orientation="vertical" >    <EditText          android:id="@+id/myInput"        android:layout_width="fill_parent"         android:layout_height="wrap_content"  />    <Button          android:id="@+id/myButton"        android:layout_width="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的源碼就不貼了。

使用注入以後,代碼看上去變得很簡潔,再也沒有那一大堆findViewById之類的了。

如何進行編譯運行呢(參考https://github.com/excilys/androidannotations/wiki/CustomizeAnnotationProcessing):
(1)如果是使用javac,需要傳遞-AandroidManifestFile=/path/to/AndroidManifest.xml這個參數,指明Manifest檔案。
(2)如果是使用Eclipse,在項目上點擊右鍵->Properties->Java Compiler->Annotation Processing->Enable annotation processing,
然後在Factory Path中添加AndroidAnnotations的jar包。
(3)如果是使用maven,maven-compiler-plugin的3.1版本可以設定編譯參數。
<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>
所有的可用的參數如下:
trace:boolean,用來啟用或者禁用@Trace註解,這個註解用會通過log記錄方法的執行。
androidManifestFile:string,預設情況下,AndroidAnnotations會在它的父資料夾中遞迴尋找AndroidManifest.xml,假如你的工程的結構比較特殊,可以用這個進行指定。
resourcePackageName:string,預設情況下,AndroidAnnotations會從AndroidManifest.xml檔案中提取應用的package來找到R檔案,假如R檔案是在一個定製的package中,可以用它來設定。
logFile:string,從3.0開始,AndroidAnnotations使用自訂的logger來在記錄代碼執行過程中的日誌。日誌預設會寫在{outputFolder}/androidannotations.log檔案中。
{outputFolder}參數按照下面的順序進行尋找:target-> build -> bin -> root project folder。如果找不到{outputFolder},可以使用logFile指定輸出的檔案。{outputFolder}可以使用預留位置來動態改變檔案名稱。
logLevel:string,enum(trace, debug, info, warn, error):預設的記錄層級是DEBUG,改為TRACE可能會有用。
logAppenderConsole:boolean,預設情況下,AndroidAnnotations會使用FileAppender和MessagerAppender2個日誌appender,FileAppender會寫在記錄檔中,MessagerAppender在IDE的訊息列表中顯示。可以設定logAppenderConsole為true來啟用另一個ConsoleAppender。
threadControl:boolean,用來啟用或者禁用@SupposeUiThread和@SupposeBackground註解,預設是true,可以保證方法是在正確的線程中調用。

3.對效能的影響
無影響!因為它的原理是產生Activity類的子類,並不是使用反射!我們可以看下編譯器幫我們自動產生的activity:
public final class MainActivity_ extends MainActivity{    @Override    public void onCreate(Bundle savedInstanceState) {        init_(savedInstanceState);//這裡會處理@StringRes,@ColorRes等等        super.onCreate(savedInstanceState);        setContentView(layout.activity_main);//這裡對應@EActivity(R.layout.activity_main)    }    private void init_(Bundle savedInstanceState) {        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();//這裡調用了@AfterViews標註的afterViews()方法    }    public static MainActivity_.IntentBuilder_ intent(Context context) {        return new MainActivity_.IntentBuilder_(context);    }    public static class IntentBuilder_ {//這個是給startActivity和startActivityForResult用的        private Context context_;        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) {                ((Activity) context_).startActivityForResult(intent_, requestCode);            } else {                context_.startActivity(intent_);            }        }    }}

最後看一下完整的pom.xml的例子(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>


android-annotations使用入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.