SupportAnnotation和AndroidAnnotations

截個圖,大概annotations 包中有40個註解,看名稱通常就知道是幹什麼的了, html

這個是 support-annotations-23.1.1 中的全部的註解, android

===================另一個開源的註解框架=================================git

這個開源的名稱是 androidannotations-api, 不是官方的,名字很像. 
github

官方網站 : http://androidannotations.org/, 有個對比前,對比後, 效果很誘人,想試試.api

這裏是在Android Studiozhong的配置, 併發

http://blog.csdn.net/caiwenfeng_for_23/article/details/45801151app

有一些注意的就是, 對Activity的註解以後, 須要在Activity後面加上"_",清單中對Activity註冊也要加上"_"框架

而後就是被人吐槽的Rest Api ,應該只支持簡單的聯網處理, 複雜的用這個就不行了,dom

而後這裏還有一個出bug 的問題,ide

http://blog.csdn.net/caiwenfeng_for_23/article/details/47681161

而後這兒有個一系列教程,2天了,終於找到一個系列了,這個至關詳細了:

  1.  http://zhenhappy.github.io/2015/10/11/Android-Annotations-1-Introduce.html

  2. http://zhenhappy.github.io/2015/10/12/Android-Annotations-2-Eclipse.html

  3. http://zhenhappy.github.io/2015/10/13/Android-Annotations-3-Android-Studio.html

  4. http://zhenhappy.github.io/2015/10/20/Android-Annotations-4-@EActivity.html

  5. http://zhenhappy.github.io/2015/11/05/Android-Annotations-5-@ViewById-@ViewsById.html

  6. http://zhenhappy.github.io/2015/11/07/Android-Annotations-6-@Click.html

  7. http://zhenhappy.github.io/2015/11/29/Android-Annotations-7-Threading.html

而後,這個頁面包含了絕大部分註解的詳情:

http://www.csdn123.com/html/topnews201408/29/729.htm

粘貼過來:

@EActivity

@EActivity(R.layout.main)
public class MyActivity extends Activity {}

@fragment

@EFragment(R.layout.my_fragment_layout)
public class MyFragment extends Fragment {}

註冊:

<fragment
        android:id="@+id/myFragment"
        android:name="com.company.MyFragment_"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

建立:

MyFragment fragment = new MyFragment_();


@EBean

普通類:

@EBean
public class MyClass {}

注意:這個類必須僅僅只能有一個構造函數,參數最多有一個context。

Activity中使用:

@EActivity
public class MyActivity extends Activity {
  @EBean
  MyOtherClass myOtherClass;
}

也能夠用來聲明接口:

@EBean(MyImplementation.class)
MyInterface myInterface;


@RootContext

在普通類中還能夠注入根環境:

@EBean
public class MyClass {
  @RootContext
  Context context;
  // Only injected if the root context is an activity
  @RootContext
  Activity activity;
  // Only injected if the root context is a service
  @RootContext
  Service service;
  // Only injected if the root context is an instance of MyActivity
  @RootContext
  MyActivity myActivity;
}


@AfterInject

若是想在類建立時期作一些操做能夠:

@AfterInject
public void doSomethingAfterInjection() {
   // notificationManager and dependency are set
}


scope 

單例類須要以下聲明:

@EBean(scope = Scope.Singleton)
public class MySingleton {}


注意:在單例類裏面不能夠注入view和事件綁定,由於單例的生命週期比Activity和Service的要長,以避免發生內存溢出。

@EView

@EViewpublic class CustomButton extends Button {
        @App
        MyApplication application;
        @StringRes
        String someStringResource;
    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }}

註冊:

<com.androidannotations.view.CustomButton_
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

建立:

CustomButton button = CustomButton_.build(context);


@EViewGroup

@EViewGroup(R.layout.title_with_subtitle)
public class TitleWithSubtitle extends RelativeLayout {
    @ViewById
    protected TextView title, subtitle;

    public TitleWithSubtitle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public void setTexts(String titleText, String subTitleText) {
        title.setText(titleText);
        subtitle.setText(subTitleText);
    }
}


註冊:

<com.androidannotations.viewgroup.TitleWithSubtitle_
        android:id="@+id/firstTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


@EApplication

@EApplication
public class MyApplication extends Application {}

Activity中使用:

@EActivity
public class MyActivity extends Activity {
  @App
  MyApplication application;}


@EService

@EServicepublic class MyService extends Service {}


跳轉service:

MyService_.intent(getApplication()).start();


中止service:

MyService_.intent(getApplication()).stop();


@EReceiver

@EReceiverpublic class MyReceiver extends BroadcastReceiver {}


@Receiver

能夠替代聲明BroadcastReceiver

@EActivitypublic class MyActivity extends Activity {

  @Receiver(actions = "org.androidannotations.ACTION_1")
  protected void onAction1() {

  }}


@EProvider

@EProviderpublic class MyContentProvider extends ContentProvider {}


@ViewById

@EActivitypublic class MyActivity extends Activity {

  // Injects R.id.myEditText,變量名稱必須和佈局的id名稱一致
  @ViewById
  EditText myEditText;

  @ViewById(R.id.myTextView)
  TextView textView;}


@AfterViews

@EActivity(R.layout.main)public class MyActivity extends Activity {

    @ViewById
    TextView myTextView;

    @AfterViews
    void updateTextWithDate() {//必定要在這裏進行view的一些設置,不要在oncreate()中設置,由於oncreate()在執行時 view尚未注入        myTextView.setText("Date: " + new Date());    }[...]


@StringRes

@EActivitypublic class MyActivity extends Activity {

  @StringRes(R.string.hello)
  String myHelloString;//不能設置成私有變量

  @StringRes
  String hello;}


@ColorRes

@EActivitypublic class MyActivity extends Activity {

  @ColorRes(R.color.backgroundColor)
  int someColor;

  @ColorRes
  int backgroundColor;}


@AnimationRes

@EActivitypublic class MyActivity extends Activity {

  @AnimationRes(R.anim.fadein)
  XmlResourceParser xmlResAnim;

  @AnimationRes
  Animation fadein;}


@DimensionRes

@EActivitypublic class MyActivity extends Activity {

  @DimensionRes(R.dimen.fontsize)
  float fontSizeDimension;

  @DimensionRes
  float fontsize;}


@DImensionPixelOffsetRes

@EActivitypublic class MyActivity extends Activity {

  @DimensionPixelOffsetRes(R.string.fontsize)
  int fontSizeDimension;

  @DimensionPixelOffsetRes
  int fontsize;}


@DimensionPixelSizeRes

@EActivitypublic class MyActivity extends Activity {

  @DimensionPixelSizeRes(R.string.fontsize)
  int fontSizeDimension;

  @DimensionPixelSizeRes
  int fontsize;}


其餘的Res:

  • @BooleanRes

  • @ColorStateListRes

  • @DrawableRes

  • @IntArrayRes

  • @IntegerRes

  • @LayoutRes

  • @MovieRes

  • @TextRes

  • @TextArrayRes

  • @StringArrayRes


@Extra

@EActivitypublic class MyActivity extends Activity {

  @Extra("myStringExtra")
  String myMessage;

  @Extra("myDateExtra")
  Date myDateExtraWithDefaultValue = new Date();}


或者:

@EActivity
public class MyActivity extends Activity {
  // The name of the extra will be "myMessage",名字必須一致
  @Extra
  String myMessage;}

傳值:

MyActivity_.intent().myMessage("hello").start() ;


@SystemService

@EActivitypublic class MyActivity extends Activity {//
  @SystemService
  NotificationManager notificationManager;}


@HtmlRes

@EActivitypublic class MyActivity extends Activity {

  // Injects R.string.hello_html
  @HtmlRes(R.string.hello_html)
  Spanned myHelloString;

  // Also injects R.string.hello_html
  @HtmlRes
  CharSequence helloHtml;}


@FromHtml

@EActivity
public class MyActivity extends Activity {//必須用在TextView

  @ViewById(R.id.my_text_view)
  @FromHtml(R.string.hello_html)
  TextView textView;

  // Injects R.string.hello_html into the R.id.hello_html view
  @ViewById
  @FromHtml
  TextView helloHtml;}


@NonConfigurationInstance

public class MyActivity extends Activity {//等同於 Activity.onRetainNonConfigurationInstance()

  @NonConfigurationInstance
  Bitmap someBitmap;

  @NonConfigurationInstance
  @Bean
  MyBackgroundTask myBackgroundTask;}


@HttpsClient

@HttpsClientHttpClient httpsClient;


示例:

@EActivity
public class MyActivity extends Activity {

    @HttpsClient(trustStore=R.raw.cacerts,
        trustStorePwd="changeit", 
        hostnameVerif=true)
    HttpClient httpsClient;

    @AfterInject
    @Background
    public void securedRequest() {
        try {
            HttpGet httpget = new HttpGet("https://www.verisign.com/");
            HttpResponse response = httpsClient.execute(httpget);
            doSomethingWithResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @UiThread
    public void doSomethingWithResponse(HttpResponse resp) {
        Toast.makeText(this, "HTTP status " + resp.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show();
    }}


@FragmentArg

@EFragmentpublic class MyFragment extends Fragment {//等同於 Fragment Argument

  @FragmentArg("myStringArgument")
  String myMessage;

  @FragmentArg
  String anotherStringArgument;

  @FragmentArg("myDateExtra")
  Date myDateArgumentWithDefaultValue = new Date();}
MyFragment myFragment = MyFragment_.builder()
  .myMessage("Hello")
  .anotherStringArgument("World")
  .build();


@Click

@Click(R.id.myButton)void myButtonWasClicked() {
    [...]}@Clickvoid anotherButton() {//若是不指定則函數名和id對應
    [...]}@Clickvoid yetAnotherButton(View clickedView) {
    [...]}


其餘點擊事件:

  • Clicks with @Click

  • Long clicks with @LongClick

  • Touches with @Touch


AdapterViewEvents 

  • Item clicks with @ItemClick

  • Long item clicks with @ItemLongClick

  • Item selection with @ItemSelect

有兩種方式調用:

1.

@EActivity(R.layout.my_list)public class MyListActivity extends Activity {

    // ...

    @ItemClick
    public void myListItemClicked(MyItem clickedItem) {//MyItem是adapter的實體類,等同於adapter.getItem(position)

    }

    @ItemLongClick
    public void myListItemLongClicked(MyItem clickedItem) {

    }

    @ItemSelect
    public void myListItemSelected(boolean selected, MyItem selectedItem) {

    }}


2.

@EActivity(R.layout.my_list)public class MyListActivity extends Activity {

    // ...

    @ItemClick
    public void myListItemClicked(int position) {//位置id

    }

    @ItemLongClick
    public void myListItemLongClicked(int position) {

    }

    @ItemSelect
    public void myListItemSelected(boolean selected, int position) {

    }}


@SeekBarProgressChange

//等同於SeekBar.OnSeekBarChangeListener.onProgressChanged(SeekBar, int, boolean)
@SeekBarProgressChange(R.id.seekBar)
 void onProgressChangeOnSeekBar(SeekBar seekBar, int progress, boolean fromUser) {
    // Something Here
 }

 @SeekBarProgressChange(R.id.seekBar)
 void onProgressChangeOnSeekBar(SeekBar seekBar, int progress) {
    // Something Here
 }

 @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2})
 void onProgressChangeOnSeekBar(SeekBar seekBar) {
    // Something Here
 }

 @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2})
 void onProgressChangeOnSeekBar() {
    // Something Here
 }@SeekBarTouchStart and @SeekBarTouchStop


@SeekBarTouchStart 和 @SeekBarTouchStop

接受開始和結束事件的監聽


@TextChange

@TextChange(R.id.helloTextView)
 void onTextChangesOnHelloTextView(CharSequence text, TextView hello, int before, int start, int count) {
    // Something Here
 }

 @TextChange
 void helloTextViewTextChanged(TextView hello) {
    // Something Here
 }

 @TextChange({R.id.editText, R.id.helloTextView})
 void onTextChangesOnSomeTextViews(TextView tv, CharSequence text) {
    // Something Here
 }

 @TextChange(R.id.helloTextView)
 void onTextChangesOnHelloTextView() {
    // Something Here
 }


@BeforeTextChange

@BeforeTextChange(R.id.helloTextView)
 void beforeTextChangedOnHelloTextView(TextView hello, CharSequence text, int start, int count, int after) {
    // Something Here
 }

 @BeforeTextChange
 void helloTextViewBeforeTextChanged(TextView hello) {
    // Something Here
 }

 @BeforeTextChange({R.id.editText, R.id.helloTextView})
 void beforeTextChangedOnSomeTextViews(TextView tv, CharSequence text) {
    // Something Here
 }

 @BeforeTextChange(R.id.helloTextView)
 void beforeTextChangedOnHelloTextView() {
    // Something Here
 }


@AfterTextChange

@AfterTextChange(R.id.helloTextView)
 void afterTextChangedOnHelloTextView(Editable text, TextView hello) {
    // Something Here
 }

 @AfterTextChange
 void helloTextViewAfterTextChanged(TextView hello) {
    // Something Here
 }

 @AfterTextChange({R.id.editText, R.id.helloTextView})
 void afterTextChangedOnSomeTextViews(TextView tv, Editable text) {
    // Something Here
 }

 @AfterTextChange(R.id.helloTextView)
 void afterTextChangedOnHelloTextView() {
    // Something Here
 }


@OptionsMenu和OptionsItem

@EActivity@OptionsMenu(R.menu.my_menu)public class MyActivity extends Activity {

    @OptionMenuItem
    MenuItem menuSearch;

    @OptionsItem(R.id.menuShare)
        void myMethod() {
          // You can specify the ID in the annotation, or use the naming convention
        }

    @OptionsItem
    void homeSelected() {
      // home was selected in the action bar
          // The "Selected" keyword is optional
    }

    @OptionsItem
    boolean menuSearch() {
          menuSearch.setVisible(false);
          // menuSearch was selected
          // the return type may be void or boolean (false to allow normal menu processing to proceed, true to consume it here)
          return true;
    }

    @OptionsItem({ R.id.menu_search, R.id.menu_delete })
    void multipleMenuItems() {
      // You can specify multiple menu item IDs in @OptionsItem
    }

    @OptionsItem
    void menu_add(MenuItem item) {
      // You can add a MenuItem parameter to access it
    }}


或者:

@EActivity@OptionsMenu({R.menu.my_menu1, R.menu.my_menu2})public class MyActivity extends Activity {}


@Background

執行:

void myMethod() {
    someBackgroundWork("hello", 42);}@Backgroundvoid someBackgroundWork(String aParam, long anotherParam) {
    [...]}


取消:

void myMethod() {
    someCancellableBackground("hello", 42);
    [...]
    boolean mayInterruptIfRunning = true;
    BackgroundExecutor.cancelAll("cancellable_task", mayInterruptIfRunning);}@Background(id="cancellable_task")void someCancellableBackground(String aParam, long anotherParam) {
    [...]}


非併發執行:

void myMethod() {
    for (int i = 0; i < 10; i++)
        someSequentialBackgroundMethod(i);}@Background(serial = "test")void someSequentialBackgroundMethod(int i) {
    SystemClock.sleep(new Random().nextInt(2000)+1000);
    Log.d("AA", "value : " + i);}


延遲:

@Background(delay=2000)void doInBackgroundAfterTwoSeconds() {}


@UiThread

UI線程:

void myMethod() {
    doInUiThread("hello", 42);}@UiThreadvoid doInUiThread(String aParam, long anotherParam) {
    [...]}


延遲:

@UiThread(delay=2000)void doInUiThreadAfterTwoSeconds() {}


優化UI線程:

@UiThread(propagation = Propagation.REUSE)void runInSameThreadIfOnUiThread() {}


進度值改變:

@EActivitypublic class MyActivity extends Activity {

  @Background
  void doSomeStuffInBackground() {
    publishProgress(0);
    // Do some stuff
    publishProgress(10);
    // Do some stuff
    publishProgress(100);
  }

  @UiThread
  void publishProgress(int progress) {
    // Update progress views
  }}


@OnActivityResult

@OnActivityResult(REQUEST_CODE)
 void onResult(int resultCode, Intent data) {
 }

 @OnActivityResult(REQUEST_CODE)
 void onResult(int resultCode) {
 }

 @OnActivityResult(ANOTHER_REQUEST_CODE)
 void onResult(Intent data) {
 }

 @OnActivityResult(ANOTHER_REQUEST_CODE)
 void onResult() {
 }


以上的註釋用法基本包含了日常程序中的事件綁定,用AndroidAnnotations框架能夠專一於作邏輯開發,最主要是簡化代碼編寫,容易維護。

若有問題能夠參考官方文檔https://github.com/excilys/androidannotations/wiki/Cookbook,

相關文章
相關標籤/搜索