AndroidAnnotaions框架的使用

首先,是如何导入AS(Eclipse请剁手)
在项目的.gradle之后添加如下代码
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        // replace with the current version of the Android plugin
        classpath 'com.android.tools.build:gradle:1.2.2'
        // the latest version of the android-apt plugin
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'  //添加的
    }
}

repositories {
    mavenCentral()
    mavenLocal()
}

model的.gradle中添加的部分
apply plugin: 'android-apt'
def AAVersion = '3.3.1' // change this to your desired version, for example the latest stable: 3.2

dependencies {
    apt "org.androidannotations:androidannotations: $AAVersion"
    compile "org.androidannotations:androidannotations-api: $AAVersion"
}


apt {
    arguments {
        androidManifestFile variant.outputs[ 0].processResources.manifestFile
        // if you have multiple outputs (when using splits), you may want to have other index than 0

        // If you're using flavors you should use the following line instead of hard-coded packageName
        // resourcePackageName android.defaultConfig.packageName

        // You can set optional annotation processing options here, like these commented options:
        // logLevel 'INFO'
        // logFile '/var/log/aa.log'
    }
}



之后,等download完成之后,make project之后,就可以在你项目当中欢快的使用注入了、喵喵喵。
如何使用?
详细一些介绍可以看官网 也可以看 http://www.csdn123.com/html/topnews201408/29/729.htm这个链接
我使用的版本是3.31的版本


@EActivity,为Activity添加布局

@EActivity (R.layout.activity_main)
public class MainActivity extends AppCompatActivity

@Fragment,为Fragment添加布局
@Fragment(R.layout.fragment_layout)

使用注解来findViewbyId,注意不要 private修饰
@ViewById (R.id.button)
Button bt1;

这样子就完成了初始化
不用一大堆的
还有一种是后面没有id的
比如
@ViewById
TextView textview02;
但是需要在我的布局文件中,声明的id的名字跟我的现在的变量的名字一样,否则会报空指针异常
还有就是一次性赋值

@ViewsById ({R.id.textview01, R.id.textview02})
ArrayList<TextView> list ;

@AfterViews
public void settextForTextView() {
    for (TextView tv:list)
    {
        tv.setText("hahajaha" );
    }
}

事件注册:
@Click (R.id.button)
public void startSecondActivity() {
    SenondActivity_.intent( this).start();
}
注意,启动Activity的是这样子启动的,SenondActivity_是被启动的Activity,他的实际是SenondActivity,然后,每一次添加了新的这些组件,然后要使用,就先编译一下,然后才会的SenondActivity_或者是Service_的出现
启动Service
@Click (R.id.button1)
public void startService()
{
    MyService_.intent( this).start();
}

同时,Click还可以为多个View同时添加相同的点击事件响应,下面这样子即可
@Click ({R.id. button, R.id.button1})
public void startService() {
    MyService_.intent( this).start();
}

还可以这样子
@Click ({R.id.button1, R.id.button})
public void startService(View v) {
    switch (v.getId())
    {
        case R.id.button:
            Toast.makeText(MainActivity. this,"button", Toast.LENGTH_LONG).show() ;
            break;
        case R.id. button1:
            Toast.makeText(MainActivity. this,"button1", Toast.LENGTH_LONG).show() ;
            break;
    }
}

其中参数就是真正的onClick中传递过来
还有@onLongClick,@OnTouch等事件标签。但是需要之一,一个标签只能一次注册同一个事件,比如onClick事件,一个button就只能一次,但是可以注册多个事件。

对于ListView或者是RecyclerView的onItemClick和onItemLongClick事件
可以使用@ItemClick和@ItemLongClick等标注,然后实现,方法的名字 可以 随便,参数可以为空或者是真正的对应的点击事件的参数列表,如上一般

@AfterView  这个表签的作用是在view完成初始化之后,对view做一些初始赋值,比如如下
@ViewById (R.id.textview01)
TextView textview ;
@ViewById(R.id.textview02)
TextView textView02 ;

@AfterViews
public void settextForTextView() {
    textview .setText("liweijiehahah") ;
    textView02 .setText("hehehehe") ;
}

@Extra
用于Itent的附加参数
通过如下方式传递bundle
SenondActivity_. intent( this).name(" 黎伟杰").msg( "hahah").start();
获取值通过指定这个表情,指定名字之后,编译一下,可以使用

@Extra
String msg;
@Extra
String name;

@Background标签,把该方法使用在子线程中
@Background(id="mybackgroundId")
public void doSomethingInBackground()
{
    //dosomething
}
其中id字段是可选的,假如,你这个后台线程是需要取消的(比如这个Activity销毁了你不需要这个后台线程了),就可以使用BackgroundExecutor.cancelAll(" mybackgroundId ");
取消掉当前指定id的后台线程。
默认情况下,@Background的线程是并行执行的(就是看哪一个线程争取到CPU),但是,我们可以通过@Serial指定线程是串行执行,比如
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);
}

这样子的话就可以使得子线程串行执行,就是一个线程执行完在执行下一个。
然后,我么还可以使用Delay指定子线程延后一段时间执行,比如
@Background(delay=2000)
void doInBackgroundAfterTwoSeconds() {
}

该线程就会延迟2秒之后在执行

@UIThead,把该方法使用在UI线程中
@UiThread
public void updateText() {
list.get(0 ).setText("新的 text");
}

这些方式可以被别人调用,然后就会运行在对应的注解线程,

    Delay在@UiThread中还可以附加的参数有delay,用法根上面的差不多

    Id同样,@UiThread也有一个id,用于取消,使用UiThreadExecutor.cancelAll("id");,跟上面的id用户差不多

    Propagation
示例:
@UiThread(propagation = Propagation.REUSE)
void runInSameThreadIfOnUiThread() {
}
假如当前线程是在UI线程中直接在该方法中执行操作,假如不是则通过Handler后台发送处理。不能喝delay属性一起使用,否则会失去效果。当没有该参数的时候,我们一般要保证方法运行在UI线程,就是通过handler发送消息的方式到达。

@SupposeBackground
这个也是在后台线程中运行的意思,但是比@Background 更加智能,如果被一个UI线程  调用后就会报一个异常,来给你一个提示。
他还可以添加参数增加限制,通过serial来指定那个线程可以调用该方法
例子:
@EBean
public class MyBean {

 //只能在被后台线程调用
  @SupposeBackground
  void someMethodThatShouldNotBeCalledFromUiThread() {
  //if this method will be called from the UI-thread an exception will be thrown
  }
     
//只能运行,而且id是需要为指定的
  @SupposeBackground(serial = {"serial1", "serial2"})
  void someMethodThatShouldBeCalledFromSerial1OrSerial2() {
  //if this method will be called from another thread then a background thread with a
  //serial "serial1" or "serial2", an exception will be thrown
  }
}
@SupposeUiThread
这个跟上面的类似,只能被UI线程调用
假如你需要处理他们被调用出错的处理,比如你在UI线程调用了使用 @SupposeBackground注解的方法的时候,可以通过
BackgroundExecutor.setWrongThreadListener()这个去实现错误回调,两个都是通过这个处理
一个是onUiExpected()


对于资源:比如颜色,drawable,String,StringArray等都是可以通过注解直接赋值的
例子:
@EActivity
public class MyActivity extends Activity {

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

  @DimensionPixelSizeRes
  int fontsize;

}

@EActivity
public class MyActivity extends Activity {

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

  @ColorRes
  int backgroundColor;

}
对于系统的服务,他也是支持一行代码搞定的
通过注解: @SystemService实现,作用等同于getSystemService()
比如
@SystemService
NotificationManager notificationManager;
就完成了初始化
还有很多都可以不如layoutInflater等
@EApplication声明一个Application
然后可以通过!@App引用实例化这个Application实力
比如
@EApplication
public class MyApplication extends Application {
...
}

然后,通过
@App
MyApplication application;
就得到了实例
EBean
用这个符号来声明非android标准组件,比如自定义的一个class
但是该类只能有一个构造方法,而且只能有一个参数(Context)或者是没有参数
声明和使用(可以嵌套)
@EBean
public class MyOtherClass {

  @Bean
  MyClass myClass;

}
使用:
@Bean
MyOtherClass myOtherClass;
就完成了实例化

还有一些很杂的
比如@InstanceState,这个注解可以在我们的Activity或者Fragment被销毁的时候保存,用于变量注解。
@WindowFeature,设置我们的窗口
@NoTitle设置窗口无标题
@Fullscreen设置全屏
等等等
最后,AndroidAnnotation还集成了一套网络请求机制。
@Rest
里面有很多的关于发送请求,参数,body的设置等等,自己去看看文档吧。

最后列出所有的注解:
Enhanced components
@EActivity
@EApplication
@EBean
@EFragment
@EProvider
@EReceiver
@EIntentService
@EService
@EView
@EViewGroup

Injection
@AfterExtras
@AfterInject
@AfterViews
@App
@Bean
@Extra
@FragmentArg
@FragmentById
@FragmentByTag
@FromHtml
@HttpsClient
@NonConfigurationInstance
@RootContext
@SystemService
@ViewById
@ViewsById

Event binding
@TextChange
@AfterTextChange
@BeforeTextChange
@EditorAction
@FocusChange
@CheckedChange
@Touch
@Click
@LongClick
@ItemClick
@ItemLongClick
@ItemSelect
@OptionsItem
@SeekBarProgressChange
@SeekBarTouchStart
@SeekBarTouchStop
@KeyDown
@KeyUp
@KeyLongPress
@KeyMultiple

Threading
@Background
@UiThread
@SupposeBackground
@SupposeUiThread

Misc
@InstanceState
@WindowFeature
@Fullscreen
@CustomTitle
@InjectMenu
@OptionsMenu
@OptionsMenuItem
@OrmLiteDao
@RoboGuice
@Trace
@Transactional
@OnActivityResult
@OnActivityResult.Extra
@HierarchyViewerSupport
@ServiceAction
@Receiver
@Receiver.Extra
@ReceiverAction
@ReceiverAction.Extra
@IgnoredWhenDetached
@WakeLock

Resource injection
@StringRes
@AnimationRes
@ColorRes
@DimensionPixelOffsetRes
@DimensionPixelSizeRes
@DimensionRes
@BooleanRes
@ColorStateListRes
@DrawableRes
@IntArrayRes
@IntegerRes
@LayoutRes
@MovieRes
@StringArrayRes
@TextArrayRes
@TextRes
@HtmlRes

Rest API
@Rest
@RestService
@Get
@Post
@Put
@Patch
@Delete
@Options
@Head
@Accept
@RequiresHeader
@RequiresCookie
@RequiresCookieInUrl
@RequiresAuthentication
@SetsCookie
@RequiresCookieInUrl
@Path
@Body
@Field
@Part
@Header
@Headers

Typesafe SharedPreferences
@DefaultBoolean
@DefaultFloat
@DefaultInt
@DefaultLong
@DefaultString
@DefaultStringSet
@DefaultRes
@Pref
@SharedPref

Preference API helpers
@PreferenceScreen
@PreferenceHeaders
@PreferenceByKey
@PreferenceChange
@PreferenceClick
@AfterPreferences
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值