Android Annotations淺析

來源:互聯網
上載者:User

標籤:android annotation   android   架構   注入   


這陣子遇到了好多事情,挺久沒來更新博文了,這兩天在學這個開源架構Android Annotations,用起來感覺挺方便的,

相信用過Spring註解的孩子理解起來應該比較容易!就是配置起來比較吃力。

關於AndroidAnnotaions的介紹,網上已經很多了,我這裡不再累贅。

  1、AndroidAnnotations官網:http://androidannotations.org/(也許你需要翻牆)

  2、eclipse中使用androidannotations的配置方法說明:https://github.com/excilys/androidannotations/wiki/Eclipse-Project-Configuration

  3、Android Studio中配置AndroidAnnotations:(這個是我這篇博文中要涉及到的!)


一、Android Studio配置androidannotations環境。

1、首先你建立一個module之後,在對應的app中會有一個名為build.gradle的檔案(該module有效),而在整個項目外面也會有一個名為build.gradle的檔案(全域有效)【這個工具中的application的目錄下(相當於Eclipse下的workspace)是可以有多個module的(相當於Eclipse下的project)】

2、我們配置的時候大概要分為下面兩步

在局部build.gradle中(加入紅色字型部分):

apply plugin: ‘com.android.application‘
apply plugin: ‘android-apt‘
def AAVersion = ‘3.0.1‘



android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"


    defaultConfig {
        applicationId "com.tongbu.mytest"
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘
        }
    }
}


dependencies {
    compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])
    compile ‘com.android.support:appcompat-v7:19.+‘

    apt "org.androidannotations:androidannotations:$AAVersion"
    compile "org.androidannotations:androidannotations-api:$AAVersion"

}


apt {
    arguments {
        androidManifestFile variant.processResources.manifestFile
        resourcePackageName ‘com.tongbu.mytest‘
    }
}


在全域build.gradle中(加入紅色字型部分):

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath ‘com.android.tools.build:gradle:0.12.+‘
        classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.3‘
    }
}


allprojects {
    repositories {
        jcenter()
    }
}


如果以上的都順利完成了,那麼恭喜你已經快配置完了,還需要把AndroidManifest.xml中的Activity的名字後面加上 _(底線),因為這個架構解析編譯的時候,比如類MainActivity會被解析成MainActivity_.class,所以在資訊清單檔中我們要在Activity的名字後面加一個底線,或者androidannotation會報錯!

但並不會這麼順利,在你補充完底線之後,你會發現會提示你找不到MainActivity_這個東東

那麼怎麼辦呢??我們說了它是在編譯的時候整出來的,那我們只要按一下編譯的按鈕即可產生了!!



這樣子androidannotation在android studio上的環境就配置好了,Eclipse的話資料比較多,再這裡就不介紹了


二、一個Demo來瞭解androidannotations的部分註解

@NoTitle  //無標題@Fullscreen //全屏@EActivity(R.layout.activity_my)public class MyActivity extends ActionBarActivity {    //==============================================基本的註解=================================================    @ViewById    Button button1;    @ViewById    Button button2;    @ViewById(R.id.textview1)   //指定id的注入    TextView textView;    @ViewById    ProgressBar progressBar;    @ViewById    ImageView imageView;    //擷取系統service的方法(取代原來的clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);)    @SystemService    ClipboardManager clipboardManager;    @Click({R.id.button1,R.id.button2,R.id.button3,R.id.button4})    public void simpleButtonOnClicked(View view){        switch (view.getId()){            case R.id.button1:{                textView.setText("Button1 is Clicked!");            }            break;            case R.id.button2:{                textView.setText("Button2 is Clicked!");            }            break;            case R.id.button3:{                String content = clipboardManager.getText().toString();                Toast.makeText(getApplicationContext(),"剪貼簿內容: " + content, Toast.LENGTH_SHORT).show();            }            break;            case R.id.button4:{                Toast.makeText(getApplicationContext(),"捲軸開始了!",Toast.LENGTH_SHORT).show();                progressBarWorks();            }            break;        }    }    @LongClick({R.id.button2})    public void buttonOnLongClicked(View view){        switch (view.getId()){            case R.id.button1:{                textView.setText("Button1 is LongClicked!");//由於沒註冊,所以不可能被觸發            }            break;            case R.id.button2:{                textView.setText("Button2 is LongClicked!");//可觸發            }            break;        }    }    //===================================================關於資源的註解=========================================    @AnimationRes(R.anim.rotate)    Animation animationRotate;    @DrawableRes(R.drawable.myphoto)    Drawable myphoto;    @ColorRes(R.color.love)    Integer mycolor;    @TextRes(R.string.textres)    CharSequence text;    @Click({R.id.button5,R.id.button6,R.id.button7})    public void animationButtonOnClicked(View view){        switch (view.getId()){            case R.id.button5:{                imageView.startAnimation(animationRotate);            }            break;            case R.id.button6:{                imageView.setImageDrawable(myphoto);            }            break;            case R.id.button7:{                Toast.makeText(getApplicationContext(),text.toString(),Toast.LENGTH_SHORT).show();            }            break;        }    }    //==============================================關於線程的註解================================================    //相當於一個新的任務AsyncTask或者新線程Thread    @Background    public void progressBarWorks(){        //相當於一個新的線程中執行: @Background        int i = 1;        while (i <= 10){            Log.e("progress","進度: " + i);            try {                Thread.sleep(1000);                updateProgressBar(i);                //直接progressBar.setProgress(i);也可以的,所以@Background註解內部可能實現了handler機制                i++;            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    //指代UI線程    @UiThread    public void updateProgressBar(int i){        progressBar.setProgress(i);        if (i == 10){            Toast.makeText(getApplicationContext(), "捲軸結束",Toast.LENGTH_SHORT).show();        }    }    //=======================================關於幾個事件的先後順序===============================================    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.e("FirstToLast", "onCreate");        //可省略!        //setContentView(R.layout.activity_my);        //progressBar.setMax(100);  報錯,null 指標異常        //因為在onCreate()被調用的時候,@ViewById還沒有被set,也就是都為null        //所以如果你要對組件進行一定的初始化,那麼你要用@AfterViews註解    }    @AfterViews    public void init(){        Log.e("FirstToLast","init");        progressBar.setMax(10);    }    @Override    protected void onResume() {        super.onResume();        Log.e("FirstToLast","onResume");    }    @Override    protected void onStart() {        super.onStart();        Log.e("FirstToLast","onStart");    }}


幾個方法的先後調用順序:



資源涉及的註解(不一一列舉):


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.