您的位置:首页 > 移动开发 > Android开发

AndroidAnnotations简单示例

2015-11-18 17:19 148 查看
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {

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

@ViewById //不指定ID,默认以控件名进行查找
Button button;

@StringRes //获取资源文件值
String hello_world;

@SystemService //实例化系统服务
NotificationManager notificationManager;

@SystemService
WindowManager windowManager;

DisplayMetrics dm;

@Click//事件控制,可以以按钮的id作为方法名
public void buttonClicked() {
textView.setText("值变了" + hello_world);
Toast.makeText(MainActivity.this, "hello ", Toast.LENGTH_LONG).show();

someBackgroundWork("丽丽", 5);
}

@AfterViews //初始化控件值
public void init() {
textView.setText("初始值 " + dm.widthPixels + " X " + dm.heightPixels);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

dm = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(dm);
}

@Background //开启新线程后台运行,而且返回值类型一定是void
void someBackgroundWork(String name, long timeToDoSomeLongComputation) {

SystemClock.sleep(timeToDoSomeLongComputation);

updateUi("hello " + name, Color.RED);
showNotificationsDelayed();
}

@UiThread
//UI线程
void updateUi(String message, int color) {

textView.setText(message);
textView.setTextColor(color);

}

@UiThread(delay = 2000)
//可以设置延时时间,以毫秒为单位
void showNotificationsDelayed() {
Notification notification = new Notification(R.mipmap.ic_launcher, "Hello !", 0);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello World!", contentIntent);
notificationManager.notify(1, notification);
}
}


注意:

使用AndroidAnnotations,编译的时候会生成一个子类,这个子类的名称就是在原来的类之后加了一个下划线“_”,比如这个例子产生的子类名称为“MainActivity_”,这就需要你在注册这个Activity的时候,在

AndroidManifest.xml中将 MainActivity 改为 MainActivity_ ,使用的时候也是使用MainActivity_来表示此类,如:

startActivity(new Intent(this,MainActivity_.class));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: