依赖注入框架之androidannotations
主页: http://androidannotations.org/
用途:
1. 使用依赖注入Views,extras,System
Service,resources
2. 简化线程模型
3. 事件绑定
4. REST Client
配置:
1. 在**project/build.gradle**文件中按下图所示添加代码:
mavenCentral()
classpath
'com.neenbedankt.gradle.plugins:android-apt:1.8'
mavenCentral()
mavenLocal()
2. 在**app/build.gradle**文件中按下图所示添加代码:
apply plugin:
'android-apt'
apt
{
arguments
{
androidManifestFile
variant.outputs[0]?.processResources?.manifestFile
}
}
apt
"org.androidannotations:androidannotations:4.0.0"
compile
"org.androidannotations:androidannotations-api:4.0.0"
* 注意事项:
*
Manifest中注册的activity要在原类名后追加下划线”_”
* 使用注解的控件和方法不能使用private修饰符
*
大型项目并不适用
示例代码:
注意导包导入的是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import org.androidannotations.annotations...... @Fullscreen //全屏 @WindowFeature (Window.FEATURE_NO_TITLE) //Activity没有标题 @EActivity (R.layout.my_activity) //布局文件在这里声明,不用在setContentView public class MyActivity extends Activity { @ViewById //初始化控件,不需要自己实例化 EditText myEditText; @ViewById (R.id.myTextView) //提供id来生成控件,如果不指定ID,默认以控件名进行查找,如上面的myEditText TextView textView; @StringRes (R.string.app_name) //字符串资源 String appName; @ColorRes (R.color.colorAccent) //颜色资源 int androidColor; @BooleanRes boolean someBoolean; @SystemService //系统服务 NotificationManager notificationManager; @Click //事件控制,可以以按钮的id作为方法名,同时支持的事件还有onLongClick,onTextChange等 void myButtonClicked() { String name = myEditText.getText().toString(); setProgressBarIndeterminateVisibility( true ); someBackgroundWork(name, 5 ); } @ViewById (R.id.textView) TextView tv; @Click (R.id.button) void submit() { tv.setText(appName); someBackgroundWork(); } @Background //开启新线程后台运行,注意不要引用UI控件,而且返回值类型一定是void void someBackgroundWork() { try { Thread.sleep( 2000 ); } catch (InterruptedException e) {} updateUi(appName, androidColor); } @UiThread //UI线程 void updateUi(String message, int color) { tv.setText(message); tv.setTextColor(color); } @LongClick void startExtraActivity() { Intent intent = new Intent( this , ActivityWithExtra_. class ); intent.putExtra(ActivityWithExtra.MY_DATE_EXTRA, new Date()); intent.putExtra(ActivityWithExtra.MY_STRING_EXTRA, "hello !" ); intent.putExtra(ActivityWithExtra.MY_INT_EXTRA, 42 ); startActivity(intent); } @Touch void myTextView(MotionEvent event) { Log.d( "MyActivity" , "myTextView was touched!" ); } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步