AndroidAnnotations简单示例
1 @EActivity(R.layout.activity_main) 2 public class MainActivity extends Activity { 3 4 @ViewById(R.id.textView) 5 TextView textView; 6 7 @ViewById //不指定ID,默认以控件名进行查找 8 Button button; 9 10 11 @StringRes //获取资源文件值 12 String hello_world; 13 14 @SystemService //实例化系统服务 15 NotificationManager notificationManager; 16 17 18 @SystemService 19 WindowManager windowManager; 20 21 DisplayMetrics dm; 22 23 @Click//事件控制,可以以按钮的id作为方法名 24 public void buttonClicked() { 25 textView.setText("值变了" + hello_world); 26 Toast.makeText(MainActivity.this, "hello ", Toast.LENGTH_LONG).show(); 27 28 someBackgroundWork("丽丽", 5); 29 } 30 31 @AfterViews //初始化控件值 32 public void init() { 33 textView.setText("初始值 " + dm.widthPixels + " X " + dm.heightPixels); 34 } 35 36 @Override 37 protected void onCreate(Bundle savedInstanceState) { 38 super.onCreate(savedInstanceState); 39 40 dm = new DisplayMetrics(); 41 windowManager.getDefaultDisplay().getMetrics(dm); 42 } 43 44 @Background //开启新线程后台运行,而且返回值类型一定是void 45 void someBackgroundWork(String name, long timeToDoSomeLongComputation) { 46 47 SystemClock.sleep(timeToDoSomeLongComputation); 48 49 updateUi("hello " + name, Color.RED); 50 showNotificationsDelayed(); 51 } 52 53 54 @UiThread 55 //UI线程 56 void updateUi(String message, int color) { 57 58 textView.setText(message); 59 textView.setTextColor(color); 60 61 } 62 63 64 @UiThread(delay = 2000) 65 //可以设置延时时间,以毫秒为单位 66 void showNotificationsDelayed() { 67 Notification notification = new Notification(R.mipmap.ic_launcher, "Hello !", 0); 68 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0); 69 notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello World!", contentIntent); 70 notificationManager.notify(1, notification); 71 } 72 }
注意:
使用AndroidAnnotations,编译的时候会生成一个子类,这个子类的名称就是在原来的类之后加了一个下划线“_”,比如这个例子产生的子类名称为“MainActivity_”,这就需要你在注册这个Activity的时候,在
AndroidManifest.xml中将 MainActivity 改为 MainActivity_ ,使用的时候也是使用MainActivity_来表示此类,如:
1 startActivity(new Intent(this,MainActivity_.class));