最近新入职一家公司,公司的项目中使用了androidannotations,于是花了些时间查看github,然后整理出以下资料。
androidannotations是一个提升开发速度的开源框架,它可以节约出时间,让你专注于真正重要的事情;同时,通过简化你的代码,也可以便于后期的维护。
首先,我们来看看AndroidAnnotations使用前和使用后的两端代码。
Before
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
ListView bookmarkList;
EditText search;
BookmarkApplication application;
Animation fadeIn;
ClipboardManager clipboardManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN);
setContentView(R.layout.bookmarks);
bookmarkList = (ListView) findViewById(R.id.bookmarkList);
search = (EditText) findViewById(R.id.search);
application = (BookmarkApplication) getApplication();
fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in);
clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1);
updateBookmarksButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2);
updateBookmarksButton2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
bookmarkList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> p, View v, int pos, long id) {
Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos);
bookmarkListItemClicked(selectedBookmark);
}
});
initBookmarkList();
}
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
void updateBookmarksClicked() {
UpdateBookmarksTask task = new UpdateBookmarksTask();
task.execute(search.getText().toString(), application.getUserId());
}
private static final String BOOKMARK_URL = //
"http://www.bookmarks.com/bookmarks/{userId}?search={search}";
class UpdateBookmarksTask extends AsyncTask {
@Override
protected Bookmarks doInBackground(String... params) {
String searchString = params[0];
String userId = params[1];
RestTemplate client = new RestTemplate();
HashMap args = new HashMap();
args.put("search", searchString);
args.put("userId", userId);
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity request = new HttpEntity(httpHeaders);
ResponseEntity response = client.exchange( //
BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args);
Bookmarks bookmarks = response.getBody();
return bookmarks;
}
@Override
protected void onPostExecute(Bookmarks result) {
adapter.updateBookmarks(result);
bookmarkList.startAnimation(fadeIn);
}
}
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}
After
@Fullscreen
@EActivity(R.layout.bookmarks)
@WindowFeature(Window.FEATURE_NO_TITLE)
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
@ViewById
ListView bookmarkList;
@ViewById
EditText search;
@App
BookmarkApplication application;
@RestService
BookmarkClient restClient;
@AnimationRes
Animation fadeIn;
@SystemService
ClipboardManager clipboardManager;
@AfterViews
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
@Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2})
void updateBookmarksClicked() {
searchAsync(search.getText().toString(), application.getUserId());
}
@Background
void searchAsync(String searchString, String userId) {
Bookmarks bookmarks = restClient.getBookmarks(searchString, userId);
updateBookmarks(bookmarks);
}
@UiThread
void updateBookmarks(Bookmarks bookmarks) {
adapter.updateBookmarks(bookmarks);
bookmarkList.startAnimation(fadeIn);
}
@ItemClick
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}
@Rest("http://www.bookmarks.com")
public interface BookmarkClient {
@Get("/bookmarks/{userId}?search={search}")
Bookmarks getBookmarks(@Path String search, @Path String userId);
}
从上面的天后两端代码可以看出,使用androidannotations框架后,代码明显简洁了很多,让人一目了然。
看到上面的效果,相信你迫不及待地要了解androidannotations的用法了吧?下面我就介绍下androidannotations的简单用法,谈到开源框架的使用,首先当然要先配置,那么androidannotations是如何配置呢?
- 首先,在项目下的build.gradle中添加以下配置
buildscript {
repositories {
mavenCentral()
}
dependencies {
// replace with the current version of the Android plugin
classpath 'com.android.tools.build:gradle:2.3.0'
}
}
repositories {
mavenCentral()
mavenLocal()
}
- 其次,在module下的build.gradle中添加以下配置
def AAVersion = "4.3.0"
dependencies {
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 9
targetSdkVersion 25
}
}
其中,AAVersion定义了androidannotations最新版本号,在依赖中秩序应用这个变量即可,当然你也可以直接在依赖中填写版本号。
基本配置我们已经弄好了,那么,接下来,我们就需要将androidannotations应用到我们的项目中
-
首先,创建一个activity
import android.app.Activity; import android.widget.EditText; import android.widget.TextView; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; @EActivity(R.layout.main) public class MyActivity extends Activity { @ViewById(R.id.myInput) EditText myInput; @ViewById(R.id.myTextView) TextView textView; @Click void myButton() { String name = myInput.getText().toString(); textView.setText("Hello "+name); } }
-
布局文件
-
AndroidMainfest.xml文件中声明activity,但是activity不在是像以前直接写类名,而是必须在类名后加上""后缀,因为,当我们编译运行的时候,as会自动生成一个MainActivity的子类MainActivity,实际上工作的类也是这个类。(生成的类在as中是看不到的,可以在电脑上项目路径下的build目录中找到)
注:startActivity的时候,也不能直接用MainActivity,而应用该清单文件中声明的也就是加上后缀名的Activity,也就是加上后缀名的Activity,在2.4以及以后的版本后,我们也可以使用以下代码来实现跳转activity
// Starting the activity
MyListActivity_.intent(context).start();
// Building an intent from the activity
Intent intent = MyListActivity_.intent(context).get();
// You can provide flags
MyListActivity_.intent(context).flags(FLAG_ACTIVITY_CLEAR_TOP).start();
// You can even provide extras defined with @Extra in the activity
MyListActivity_.intent(context).myDateExtra(someDate).start();
从上面的讲解中,我们应该可以看出androidannotations的特点,归纳起来就是以下五点:
-
依赖注入:可以注入view,service,activity,resource
@EActivity public class MyActivity extends Activity { // ... }
-
简化线程模型:可以在方法上注释为ui线程或者background线程
void myMethod() { someBackgroundWork("hello", 42); } @Background void someBackgroundWork(String aParam, long anotherParam) { [...] }
-
事件绑定:注释方法来操作view的时间,而不在需要匿名listener类
@Click(id=) void myButton() { String name = myInput.getText().toString(); textView.setText("Hello "+name); }
轻松的客户端:创建一个客户端接口,androidannotations会生成实现类
可见:在androidannotations生成子类的时候,你可以去产看代码来观察它是如何工作。
到这,我们大概了解了android的基本使用方法,当然这只是最初步的使用,想要了解更多androidannotations的使用方法,请点击下面链接:
androidannotations的更多使用方法
项目地址