Android Annotations 注解例子

Android 最火的快速开发框架androidannotations配置详解文章中有eclipse配置步骤,Android 最火快速开发框架AndroidAnnotations简介文章中的简单介绍,本篇注重讲解AndroidAnnotations中注解方法的使用。

@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
public class MyClass {

}

注意:这个类必须仅仅只能有一个构造函数,参数最多有一个context。

Activity中使用:

@EActivity
public class MyActivity extends Activity {

  @Bean
  MyOtherClass myOtherClass;

}

也可以用来声明接口:

@Bean(MyImplementation.class)
    MyInterface myInterface;

在普通类中还可以注入根环境:

@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
  public void doSomethingAfterInjection() {
    // notificationManager and dependency are set
  }

单例类需要如下声明:

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

}

注意:在单例类里面不可以注入view和事件绑定,因为单例的生命周期比Activity和Service的要长,以免发生内存溢出。

@EView

@EView
public 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

@EService
public class MyService extends Service {

}

跳转service:

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

停止service:

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

@EReceiver

@EReceiver
public class MyReceiver extends BroadcastReceiver {

}

@Receiver

可以替代声明BroadcastReceiver

@EActivity
public class MyActivity extends Activity {

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

  }

}

@EProvider

@EProvider
public class MyContentProvider extends ContentProvider {

}

@ViewById

@EActivity
public class MyActivity extends Activity {

  // Injects R.id.myEditText,变量名称必须和布局的id名称一致
  @ViewById
  EditText myEditText;

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

  @ViewByIds({R.id.id1,R.id.id2}) List<TextView> list;
}

@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

@EActivity
public class MyActivity extends Activity {

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

  @StringRes
  String hello;

}

@ColorRes

@EActivity
public class MyActivity extends Activity {

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

  @ColorRes
  int backgroundColor;

}

@AnimationRes

@EActivity
public class MyActivity extends Activity {

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

  @AnimationRes
  Animation fadein;

}

@DimensionRes

@EActivity
public class MyActivity extends Activity {

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

  @DimensionRes
  float fontsize;

}

@DImensionPixelOffsetRes

@EActivity
public class MyActivity extends Activity {

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

  @DimensionPixelOffsetRes
  int fontsize;

}

@DimensionPixelSizeRes

@EActivity
public 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

@EActivity
public 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

@EActivity
public class MyActivity extends Activity {//
  @SystemService
  NotificationManager notificationManager;

}

@HtmlRes

@EActivity
public 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

@HttpsClient
HttpClient 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

@EFragment
public 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() {
    [...]
}
@Click
void anotherButton() {//如果不指定则函数名和id对应
    [...]
}
@Click
void 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);
}

@Background
void 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);
}

@UiThread
void doInUiThread(String aParam, long anotherParam) {
    [...]
}

延迟:

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

优化UI线程:

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

进度值改变:

@EActivity
public 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,

时间: 2024-10-13 01:24:01

Android Annotations 注解例子的相关文章

【FastDev4Android框架开发】RecyclerView完全解析之结合AA(Android Annotations)注入框架实例(三十)

(一).前言: 话说RecyclerView已经面市很久,也在很多应用中得到广泛的使用,在整个开发者圈子里面也拥有很不错的口碑,那说明RecyclerView拥有比ListView,GridView之类控件有很多的优点,例如:数据绑定,Item View创建,View的回收以及重用等机制.本系列文章会包括到以下三个部分: RecyclerView控件的基本使用,包括基础,进阶,高级部分,动画之类(点击进入) RecyclerView控件的实战实例(点击进入) RecyclerView控件集合AA

Android开发之Android Annotations框架

昨天研究了一下Volley网络通信框架的使用,今天有研究了一下Android Annotations框架,发现Android Annotations框架确实可以减少代码量. Android Annotations 是一个开源的框架,用于加速 Android 应用的开发,可以让你把重点放在功能的实现上,简化了代码,提升了可维护性. 功能模块: 1. 使用依赖注入(Dependency Injection) ----------------------------------------------

Android Annotations开源框架学习 + eclipse(一)

1.下载 相关jar包 (下载地址:https://repo1.maven.org/maven2/org/androidannotations/androidannotations-bundle/3.3.1/androidannotations-bundle-3.3.1.zip) 2.配置eclipse 在libs下导入androidannotations-api-3.3.1.jar ,在eclipse项目中 新增compile-lib 文件夹,其中放置:androidannotations-3

Hibernate Annotations 注解

Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么使用,但是hibernate中也封装了javax.persistence,而且数据库映射注释主要还是使用javax.persistence,即如下注释元素Column,使用规则如下.  分类: Java(66)  [java] view plain copy @Entity 声明当前是一个持久化类

Android Annotations浅析

这阵子遇到了好多事情,挺久没来更新博文了,这两天在学这个开源框架Android Annotations,用起来感觉挺方便的, 相信用过Spring注解的孩子理解起来应该比较容易!就是配置起来比较吃力. 关于AndroidAnnotaions的介绍,网上已经很多了,我这里不再累赘. 1.AndroidAnnotations官网:http://androidannotations.org/(也许你需要翻墙) 2.eclipse中使用androidannotations的配置方法说明:https://

Android Annotations Eclipse 配置 (3)

Android Annotations 本来我想写个 Java 版本的<RESTful客户端库:RestClient>用于 Android 应用开发,结果发现不太好写,虽然用了 Dynamic Proxy 实现了大部分功能,但是因为无法通过反射取得参数名,而且 Java 没有 DuckType ,再加上也没有方便的 Dict 类型,搞出来的东西很难看,不好用. 后来令狐给我推荐了这个 Android Annotations ,这个用 annotation 实现的方法真是好,所以想试一下,刚好在

Android通过注解初始化View

一.引言 Android中通过findViewById在布局文件中找到需要的View,加入一个Activity里面有许多的View需要初始化,那将是一件很繁琐的事情.当然Google一下你会发现有很多Android Annotations框架.比如比较有名的"Android Annotations",这样的框架很复杂,用起来也比较麻烦,还有一些BUG,第一次使用也花费了不少时间研究.也许你在项目中只希望用到 Inject View这个功能,又或者你想知道这个实现的原理是怎样的.本文主要

Android简易注解View(java反射实现)

一.引言 Android中通过findViewById在布局文件中找到需要的View,加入一个Activity里面有许多的View需要初始化,那将是一件很繁琐的事情.当然Google一下你会发现有很多Android Annotations框架.比如比较有名的“Android Annotations”,这样的框架很复杂,用起来也比较麻烦,还有一些BUG,第一次使用也花费了不少时间研究.也许你在项目中只希望用到 Inject View这个功能,又或者你想知道这个实现的原理是怎样的.本文主要是解决这两

使用Android Annotations开发

使用Android Annotations框架gradle配置1.修改Module下的build.gradle apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' buildscript { repositories { mavenCentral() } dependencies { classpath 'com.neenbedankt.gradle.plugins:android