下面是小编为大家整理的Android实战开发基础框架搭建,本文共5篇,以供大家参考借鉴!
篇1:Android实战开发基础框架搭建
这回的项目还是在那篇文章中展示的微博形式,不过UI改了,另外增加了不少功能,因此出来后的效果应该会比原来强很多,另外在手机版的开发完成后会开发pad版本的,加上销控功能,也就是一些房源的展示和销售等功能。注:我们这两个东西是给销售用的!
所以这回就以一种直播的方式展现出来,由于产品团队正在努力的进行着设计,所以我们先来看看一些基础的架构和代码,等产品设计完成准备开工后在把我们的需求、原型、设计图等等的东西写上来看看,大家也就能够彻底的明白我们想要做的是个什么东西了。
第一篇文章就简单的写一下我所准备好的项目基本框架,也就是说每个包里面放什么东西,有什么作用之类的,然后后续几天在未开发之前来一一介绍里面的一些主要的类,先看看截图:
1. hb.hbwb
这个包大家应该一眼就看出来了,放Activity的,别的东西不放。
2. hb.hbwb.finals
系统需要用到的一些常量,分开存放到不同的类中。
3. hb.hbwb.model
读取数据的层,由Activity调用,去请求tools下的工具,并返回需要的数据给前台。BaseModel类是一个写好的父类,以后的Model都继承他,主要是一些公用的属性方法之类的,
4. hb.hbwb.model.beans
很明显是放bean的地方,BaseBean和BaseModel一样,我们的所有数据都有可能会返回两个字段:state和error_message,也就是状态和错误信息,这里就把这两个字段放在了BaseBean中,将来的所有Bean全部继承它。
5. hb.hbwb.tools
各种功能的处理类,比如DBTool就是进行数据库操作的、XMLTool是处理提交请求获取XML数据的功能,具体的内容会在接下来的几篇日志中写一写。
目前的基础框架就是这样准备的,将来开始开发后可能也会增加一些别的包用来放SAX的处理之类的东西。现在这些功能都已经测试完了,Tools中的类都是前一版本中使用过的,不过这次进行了部分优化,同时也写了一些注释,争取这套框架能够成为比较统一好用的一套,在开发后续的pad版本时还可以继续使用。
==============================================================================
提高:1.这样分布是否合理?
2.是否具有扩展性?
摘自 ¤坏小子¨的挨踢民工生活
篇2:android 从零开始搭建框架系列(1)
工作几年发现自己没留下啥东西,天天开发开发,没总结过, 这次想总结下。故而写这个系列的博客。希望对广大的开发者有所帮助。
OK 首先先分析下 框架的作用,以及框架所应拥有的功能
框架有啥好处那,你只要写了一次以后就可以重复利用了。
无非是拷贝过来拷贝过去。写的框架必须简单易懂。
功能以及分模块:
1. 联网 模块
2. 数据缓存模块。(缓存这里比较重要,因为每次不肯能都去获取新数据,太费流量了。)
3. 图片联网获取并加载模块。以及图片的缓存
4. 数据库模块
ok 废话不多说 上点干货。下面是框架的结构图
vc341b7PwtTYSHR0cENvbXBvbmVudHOjrMi7uvOw0cbk1tC1xEh0dHBNaW1lLmphcrD8t8W1vc/uxL/W0MilPC9wPg0KPGhyIC8+DQo8cD48c3Ryb25nPs/I0LS49sGqzfi/8rzco7podHRwbWFuYWdlci0g1eK49ta7ysfTw8C0warN+LXEPC9zdHJvbmc+PC9wPg0KPHByZSBjbGFzcz0=“brush:java;”>package com.example.manager;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.util.EntityUtils;import com.example.BaseApplication;import com.example.Interface.IDownloadListener;import com.example.utils.LogUtil;import com.example.utils.NetWorkUtil;import android.http.AndroidHttpClient;/** * HttpManager 最基本的联网请求 只做最基本的联网操作 * * @author liuml * * -3-12 下午3:14:27 */public class HttpManager { private static final String TAG = “HttpManager”; public static HttpClient getDefaultHttpClient { //xxxxx 输入自己的项目名字 AndroidHttpClient httpClient = AndroidHttpClient.newInstance(“xxxxx”); // HttpClient httpClient = new DefaultHttpClient(); return httpClient; } /** * 不带参数的get请求 ** @param url * @param listener * @return */ public static String requestJsonWithGet(String url, IDownloadListener listener) { // 判断网路状态 if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {if (listener != null) { listener.onNetworkDisconnect();}return null; } String requestResult = null; HttpClient httpClient = getDefaultHttpClient(); HttpGet httpRequest = new HttpGet(url); LogUtil.d(TAG, “url = ” + url); try {HttpResponse response = httpClient.execute(httpRequest);int statusCode = response.getStatusLine().getStatusCode();LogUtil.d(TAG, “服务器返回码” + statusCode);if (HttpStatus.SC_OK == statusCode) { HttpEntity entity = response.getEntity(); if (entity != null) { requestResult = EntityUtils.toString(entity); if (listener != null) {listener.onDownloadSuccessed(requestResult); } } else { if (listener != null) {listener.onDownloadFailed(); } }} else { if (listener != null) { listener.onDownloadFailed(); }} } catch (ClientProtocolException e) {e.printStackTrace();listener.onDownloadFailed(); } catch (IOException e) {e.printStackTrace();listener.onDownloadFailed(); } finally {if (httpClient instanceof AndroidHttpClient) { ((AndroidHttpClient) httpClient).close();} } return requestResult; } /** * 带参数的get请求 ** @param url * @param getParameters * @param listener * @return */ public static String requestJsonWithGet(String url, List
然后我创建一个json管理器 jsonmanager
jsonManager主要的功能有:
创建线程池,处理联网请求,异步加载。 判断网络状态,以及 调用存储json数据的方法。 。。反正就是一系列判断。package cn.psy.xinhaijiaoyu.mamager;import java.io.File;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.apache.http.NameValuePair;import android.content.Context;import cn.psy.xinhaijiaoyu.XinHaiApplication;import cn.psy.xinhaijiaoyu.Interface.IDownloadListener;import cn.psy.xinhaijiaoyu.cache.JsonCacheManager;import cn.psy.xinhaijiaoyu.util.LogUtil;import cn.psy.xinhaijiaoyu.util.NetWorkUtil;/** * json 数据管理 * * @author liuml -2-27 * */public class JsonManager { private static final String TAG = “JsonManager”; private JsonCacheManager mJsonCacheManager; private ExecutorService mExecutorService; private static final int THREAD_POOL_SIZE = 5; public JsonManager(Context context) { mJsonCacheManager = new JsonCacheManager(context); mExecutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); } /** * 没有参数的get请求 ** @param url * @param listener */ public void loadJsonByGet(String url, IDownloadListener listener) { loadJsonByGet(url, listener, false); } /** * 有参数的get请求,无服务器判断 ** @param url * @param parameters * @param listener */ public void loadJsonByGet(final String url, final List
这是json管理器,
在哪里调用他呢?
这时候我写个类DataManager 在这里调用他
package com.example.manager;import java.io.File;import java.util.ArrayList;import java.util.List;import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair;import com.example.Interface.IDownloadListener;import com.example.config.ApiHttpConfig;import com.example.config.MyParameters;import com.example.utils.LogUtil;/** * 数据管理 * * @author liuml 2014-2-27 * */public class DataManager { private static final String TAG = “DataManager”; // private static DataManager mInstance; private JsonManager mJsonManager; public DataManager(JsonManager jsonManager) { mJsonManager = jsonManager; } /** * 登陆接口 ** @param username *用户名 * @param passwd *密码 * @param imsi *手机imsi * @param listener *回调接口 * @param formServer *是否从服务器上获取(默认为false 如果本地没有数据则从网上获取, 如果为true 则强制从网上获取) */ public void login(String username, String passwd, String imsi, IDownloadListener listener, boolean formServer) { String url = ApiHttpConfig.getInstance().loginApi(); LogUtil.d(TAG, “login url ========================== ” + url); List
这里我也只是做个登陆接口。其他接口想怎么写就怎么写
对了 还有参数的添加。添加的话需要再写一个类。
package com.example.config;import java.util.ArrayList;import java.util.List;import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair;import com.example.utils.LogUtil;public class MyParameters extends ApiHttpConfig{ private static MyParameters Parameters = new MyParameters(); public static MyParameters getInstance() { return Parameters; } /** * 登陆参数 * @param username * @param passwd * @param imsi * @return */ public List
这个类继承ApiHttpConfig 这个类是用作保存接口的地方
package com.example.config;import java.util.ArrayList;import java.util.List;import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair;import com.example.utils.LogUtil;/** * * @author liuml * * 2015-4-22 上午11:58:11 */public class ApiHttpConfig { private static ApiHttpConfig apiConfig = new ApiHttpConfig(); public static final String DefaultParserUrl = “192.168.1.1/api/mapi”; // 登录 public static final String LOGIN_PART_STRING = “/Login”; public static final String PARENT_AND_CHILD_REGIST = “/ParentRegist”; protected static final String TAG = “ApiHttpConfig”; public static ApiHttpConfig getInstance() { return apiConfig; } public String loginApi() { return DefaultParserUrl + LOGIN_PART_STRING; }}
今天就暂时写这么多吧。。ok
里面还有些缓存模块的东西 我明天再加上去吧。。等我全部写完了在吧框架代码发上去
篇3:Android 最火的快速开发框架xUtils
xUtils简介
xUtils 包含了很多实用的Android工具,
xUtils 最初源于Afinal框架,进行了大量重构,使得xUtils支持大文件上传,更全面的http请求协议支持(10种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响。
xUtils最低兼容Android 2.2 (API Level 8) 目前xUtils工具主要有四大模块:DbUtils模块
Android中的ORM框架,一行代码就可以进行增删改查
支持事务,默认关闭
可通过注解自定义表名,列名,外键,唯一性约束,NOT NULL约束,CHECK约束等(需要混淆的时候请注解表名和列名)
支持绑定外键,保存实体时外键关联实体自动保存或更新
自动加载外键关联实体,支持延时加载
支持链式表达查询,更直观的查询语义,参考下面的介绍或sample中的例子。ViewUtils模块
Android中的IOC框架,完全注解方式就可以进行UI资源和事件绑定
新的事件绑定方式,使用混淆工具混淆后仍可正常工作
目前支持常用的20种事件绑定,参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。HttpUtils模块
支持同步,异步方式的请求
支持大文件上传,上传大文件不会OOM
支持GET,POST,PUT,MOVE,COPY,DELETE,HEAD,OPTIONS,TRACE,CONNECT请求
下载支持301/302重定向,支持设置是否根据Content-Disposition重命名下载的文件
返回文本内容的请求(默认只启用了GET请求)支持缓存,可设置默认过期时间和针对当前请求的过期时间。BitmapUtils模块
加载Bitmap的时候无需考虑Bitmap加载过程中出现的OOM和Android容器快速滑动时候出现的图片错位等现象;
支持加载网络图片和本地图片
内存管理使用LRU算法,更好的管理Bitmap内存;
可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等...
使用xUtils快速开发框架需要有以下权限:
混淆时注意事项:
添加Android默认混淆配置${sdk.dir}/tools/proguard/proguard-android.txt
不要混淆xUtils中的注解类型,添加混淆配置:-keep class * extends java.lang.annotation.Annotation { *; }
对使用DbUtils模块持久化的实体类不要混淆,或者注解所有表和列名称@Table(name=xxx),@Id(column=xxx),@Column(column=xxx),@Foreign(column=xxx,foreign=xxx)
DbUtils使用方法
DbUtilsdb=DbUtils.create(this);
Useruser=newUser();//这里需要注意的是User对象必须有id属性,或者有通过@ID注解的属性
user.setEmail(wyouflf@qq);
user.setName(wyouflf);
db.save(user);// 使用saveBindingId保存实体时会为实体的id赋值...
// 查找
Parententity=db.findById(Parent.class,parent.getId());
List
list=db.findAll(Parent.class);//通过类型查找
ParentParent=db.findFirst(Selector.from(Parent.class).where(name,=,test));// IS NULL
ParentParent=db.findFirst(Selector.from(Parent.class).where(name,=,null));
// IS NOT NULL
ParentParent=db.findFirst(Selector.from(Parent.class).where(name,!=,null));// WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMIT pageSize OFFSET pageOffset
List
list=db.findAll(Selector.from(Parent.class)
.where(id,<,54)
.and(WhereBuilder.b(age,>,20).or(age, < ,30))
.orderBy(id)
.limit(pageSize)
.offset(pageSize*pageIndex));// op为in时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parenttest=db.findFirst(Selector.from(Parent.class).where(id,in,newint[]{1,2,3}));
// op为between时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parenttest=db.findFirst(Selector.from(Parent.class).where(id,between,newString[]{1,5}));DbModeldbModel=db.findDbModelAll(Selector.from(Parent.class).select(name));//select(name)只取出name列
List
...List
db.execNonQuery(sql)// 执行自定义sql
...
ViewUtils使用方法
完全注解方式就可以进行UI绑定和事件绑定。
无需findViewById和setClickListener等。 // xUtils的view注解要求必须提供id,以使代码混淆不受影响。
@ViewInject(R.id.textView)
TextView textView;//@ViewInject(vale=R.id.textView, parentId=R.id.parentView)
//TextView textView;@ResInject(id=R.string.label,type= ResType.String)
private Stringlabel;// 取消了之前使用方法名绑定事件的方式,使用id绑定不受混淆影响
// 支持绑定多个id @OnClick({R.id.id1, R.id.id2, R.id.id3})
// or @OnClick(value={R.id.id1, R.id.id2, R.id.id3}, parentId={R.id.pid1, R.id.pid2, R.id.pid3})
// 更多事件支持参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。
@OnClick(R.id.test_button)
public void testButtonClick(Viewv){ // 方法签名必须和接口中的要求一致
...
}
...
//在Activity中注入:
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewUtils.inject(this);//注入view和事件
...
textView.setText(some text...);
...
}
//在Fragment中注入:
@Override
public ViewonCreateView(LayoutInflaterinflater,ViewGroup container,BundlesavedInstanceState){
View view = inflater.inflate(R.layout.bitmap_fragment,container,false);// 加载fragment布局
ViewUtils.inject(this,view);//注入view和事件
...
}
//在PreferenceFragment中注入:
public void onActivityCreated(BundlesavedInstanceState){
super.onActivityCreated(savedInstanceState);
ViewUtils.inject(this,getPreferenceScreen());//注入view和事件
...
}
// 其他重载
// inject(View view);
// inject(Activity activity)
// inject(PreferenceActivity preferenceActivity)
// inject(Object handler, View view)
// inject(Object handler, Activity activity)
// inject(Object handler, PreferenceGroup preferenceGroup)
// inject(Object handler, PreferenceActivity preferenceActivity)
HttpUtils使用方法
普通get方法
HttpUtilshttp=newHttpUtils();
http.send(HttpRequest.HttpMethod.GET,
www.lidroid,
newRequestCallBack
@Override
publicvoidonLoading(longtotal,longcurrent,booleanisUploading){
testTextView.setText(current+/+total);
}@Override
publicvoidonSuccess(ResponseInfo
textView.setText(responseInfo.result);
}@Override
publicvoidonStart(){
}@Override
publicvoidonFailure(HttpExceptionerror,Stringmsg){
}
});
使用HttpUtils上传文件 或者 提交数据 到服务器(post方法)
RequestParamsparams=newRequestParams();
params.addHeader(name,value);
params.addQueryStringParameter(name,value);// 只包含字符串参数时默认使用BodyParamsEntity,
// 类似于UrlEncodedFormEntity(application/x-www-form-urlencoded),
params.addBodyParameter(name,value);// 加入文件参数后默认使用MultipartEntity(multipart/form-data),
// 如需multipart/related,xUtils中提供的MultipartEntity支持设置subType为related。
// 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity(如:
// MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity)。
// 例如发送json参数:params.setBodyEntity(new StringEntity(jsonStr,charset));
params.addBodyParameter(file,newFile(path));
...HttpUtilshttp=newHttpUtils();
http.send(HttpRequest.HttpMethod.POST,
uploadUrl....,
params,
newRequestCallBack
publicvoidonStart(){
testTextView.setText(conn...);
}@Override
publicvoidonLoading(longtotal,longcurrent,booleanisUploading){
if(isUploading){
testTextView.setText(upload: +current+/+total);
}else{
testTextView.setText(reply: +current+/+total);
}
}@Override
publicvoidonSuccess(ResponseInfo
testTextView.setText(reply: +responseInfo.result);
}@Override
publicvoidonFailure(HttpExceptionerror,Stringmsg){
testTextView.setText(error.getExceptionCode()+:+msg);
}
});
使用HttpUtils下载文件
支持断点续传,随时停止下载任务,开始任务 HttpUtilshttp= new HttpUtils();
HttpHandler handler = http.download(apache.dataguru/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip,
/sdcard/httpcomponents-client-4.2.5-src.zip,
true,// 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
true,// 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
new RequestCallBack
public void onStart(){
testTextView.setText(conn...);
} @Override
public void onLoading(longtotal,long current,booleanisUploading){
testTextView.setText(current+/ + total);
} @Override
public void onSuccess(ResponseInfo
testTextView.setText(downloaded:+responseInfo.result.getPath());
} @Override
public void onFailure(HttpExceptionerror,String msg){
testTextView.setText(msg);
}
});...
//调用cancel()方法停止下载
handler.cancel();
BitmapUtils 使用方法
BitmapUtilsbitmapUtils=newBitmapUtils(this);// 加载网络图片
bitmapUtils.display(testImageView,bbs.lidroid/static/image/common/logo.png);// 加载本地图片(路径以/开头, 绝对路径)
bitmapUtils.display(testImageView,/sdcard/test.jpg);// 加载assets中的图片(路径以assets开头)
bitmapUtils.display(testImageView,assets/img/wallpaper.jpg);// 使用ListView等容器展示图片时可通过PauseOnScrollListener控制滑动和快速滑动过程中时候暂停加载图片
listView.setOnScrollListener(newPauseOnScrollListener(bitmapUtils,false,true));
listView.setOnScrollListener(newPauseOnScrollListener(bitmapUtils,false,true,customListener));
输出日志 LogUtils
// 自动添加TAG,格式: className.methodName(L:lineNumber)
// 可设置全局的LogUtils.allowD = false,LogUtils.allowI = false...,控制是否输出log。
// 自定义log输出LogUtils.customLogger = new xxxLogger();
LogUtils.d(wyouflf);
参考链接:blog.csdn/dj0379/article/details/38356773篇4:Android开发之Drag&Drop框架实现拖放手势
Android3.0提供了drag/drop框架,利用此框架可以实现使用拖放手势将一个view拖放到当前布局中的另外一个view中,本文将介绍如何使用拖放框架。
一、实现拖放的步骤首先,我们先了解一下拖放过程,从官方文档可以知道,整个拖放过程共分为4个步骤,具体如下:
1、Started:启动拖放,主要是调用被拖放View的startDrag方法。此方法原型为:
public final boolean startDrag(ClipData data,
View.DragShadowBuilder shadowBuilder,
Object myLocalState,
int flags)
启动后,系统生成拖放阴影并发送action为ACTION_DRAG_STARTED的拖放事件到当前布局中已经设置了拖放监听的View。
2、Continuing:保持拖动状态。在此过程中系统可能会发送一个或多个拖动事件给设置了拖放 的View,比如ACTION_DRAG_ENTERED、ACTION_DRAG_LOCATION等。
3、Dropped:用户在目标区域内释放拖动阴影,系统会向设置了拖放 的View发送action为ACTION_DROP的事件。
4、Ended:用户释放了拖动阴影,系统会向设置了拖放 的View发送action为ACTION_DRAG_ENDED事件,完成拖放。
二、拖放过程中关键的接口和类其次,我们要了解清楚拖放过程中的几个关键的接口和类,主要有OnDragListener、DragEvent、DragShadowBuilder、ClipData、ClipDescription等。
1、OnDragListener:接口,拖放事件 。当发生Drag时,回调此接口中的方法。接口中只含有一个方法onDrag,方法原型为:
boolean onDrag(View v, DragEvent event)
参数v:设置了 的View
参数event:拖放事件的参数,封装了拖放相关的数据
返回值:true-事件已处理;false事件未处理。
2、DragEvent:拖放事件对象,根据action的不同,包含不同的事件数据。
3、DragShadowBuilder:拖放阴影构造者对象,用于构造拖放阴影。
4、ClipData、ClipDescription:用于拖放的移动数据。
三、案例展示对以上内容有了基本了解后,我们来进行如下案例,首先看效果图
如图界面内共有两个区域,灰色区域和黄色区域,图标可在灰色区域内自由拖动,并可改变自己的位置,如下图
当图标进入或离开黄色区域时,将改变颜色,效果图如下
四、案例实现下面我们看看具体如何实现:
布局文件,代码如下:
Java文件:
为ImageView绑定长点击事件
imageView.setOnLongClickListener(new OnLongClickListener { @Override public boolean onLongClick(View v) { //创建移动数据 ClipData.Item item = new ClipData.Item((String) v.getTag()); ClipData data = new ClipData(IMAGEVIEW_TAG, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item); //调用startDrag方法,第二个参数为创建拖放阴影 v.startDrag(data, new View.DragShadowBuilder(v), null, 0); return true; } });
为目标View绑定拖拽监听:
container.setOnDragListener(new OnDragListener() { @Override public boolean onDrag(View v, DragEvent event) { final int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: //拖拽开始事件 if (event.getClipDescription().hasMimeType( ClipDescription.MIMETYPE_TEXT_PLAIN)) { return true; } return false; case DragEvent.ACTION_DRAG_ENTERED: //被拖放View进入目标View container.setBackgroundColor(Color.YELLOW); return true; case DragEvent.ACTION_DRAG_LOCATION: return true; case DragEvent.ACTION_DRAG_EXITED: //被拖放View离开目标View container.setBackgroundColor(Color.BLUE); title.setText(“”); return true; case DragEvent.ACTION_DROP: //释放拖放阴影,并获取移动数据 ClipData.Item item = event.getClipData().getItemAt(0); String dragData = item.getText().toString(); title.setText(dragData+event.getY()+“:”+event.getX()); return true; case DragEvent.ACTION_DRAG_ENDED: //拖放事件完成 return true; default: break; } return false; } });五、源码下载
想要动手实践的小伙伴,可以点击“源码下载”下载完整工程测试,
电脑资料
篇5:Android 最火的快速开发框架AndroidAnnotations使用
Android 最火的快速开发框架androidannotations配置详解文章中有eclipse配置步骤,Android 最火快速开发框架AndroidAnnotations简介文章中的简单介绍,本篇注重讲解AndroidAnnotations中注解方法的使用,
@EActivity
示例:
@EActivity(R.layout.main)public class MyActivity extends Activity {}@fragment
示例:
@EFragment(R.layout.my_fragment_layout) public class MyFragment extends Fragment { }注册:
创建:
MyFragment fragment = new MyFragment_();
普通类:
@EBeanpublic class MyClass {}注意:这个类必须仅仅只能有一个构造函数,参数最多有一个context。
Activity中使用:
@EActivitypublic class MyActivity extends Activity { @Bean MyOtherClass myOtherClass;}
也可以用来声明接口:
@Bean(MyImplementation.class) MyInterface myInterface;
在普通类中还可以注入根环境:
@EBeanpublic class MyClass { @RootContext Context context; // Only injected if the root context is an activity @RootContext Activity activity; // Only injected if the root context is a service @RootContext Service service; // Only injected if the root context is an instance of MyActivity @RootContext MyActivity myActivity;}
如果想在类创建时期做一些操作可以:
@AfterInject public void doSomethingAfterInjection() { // notificationManager and dependency are set }
单例类需要如下声明:
@EBean(scope = Scope.Singleton)public class MySingleton {}
注意:在单例类里面不可以注入view和事件绑定,因为单例的生命周期比Activity和Service的要长,以免发生内存溢出。
@EView
@EViewpublic class CustomButton extends Button { @App MyApplication application; @StringRes String someStringResource; public CustomButton(Context context, AttributeSet attrs) { super(context, attrs); }}
注册:
创建:
CustomButton button = CustomButton_.build(context);
@EViewGroup
@EViewGroup(R.layout.title_with_subtitle)public class TitleWithSubtitle extends RelativeLayout { @ViewById protected TextView title, subtitle; public TitleWithSubtitle(Context context, AttributeSet attrs) { super(context, attrs); } public void setTexts(String titleText, String subTitleText) { title.setText(titleText); subtitle.setText(subTitleText); }}
注册:
@EApplication@EApplicationpublic class MyApplication extends Application {}Activity中使用:
@EActivitypublic class MyActivity extends Activity { @App MyApplication application;}
@EService
@EServicepublic class MyService extends Service {}
跳转service:
MyService_.intent(getApplication()).start();
停止service:
MyService_.intent(getApplication()).stop();
@EReceiver
@EReceiverpublic class MyReceiver extends BroadcastReceiver {}
@Receiver可以替代声明BroadcastReceiver
@EActivitypublic class MyActivity extends Activity { @Receiver(actions = org.androidannotations.ACTION_1) protected void onAction1() { }}
@EProvider
@EProviderpublic class MyContentProvider extends ContentProvider {}
@ViewById
@EActivitypublic class MyActivity extends Activity { // Injects R.id.myEditText,变量名称必须和布局的id名称一致 @ViewById EditText myEditText; @ViewById(R.id.myTextView) TextView textView;}
@AfterViews
@EActivity(R.layout.main)public class MyActivity extends Activity { @ViewById TextView myTextView; @AfterViews void updateTextWithDate() {
//一定要在这里进行view的一些设置,不要在oncreate()中设置,因为oncreate()在执行时 view还没有注入
myTextView.setText(Date: + new Date()); }[...]
@StringRes
@EActivitypublic class MyActivity extends Activity { @StringRes(R.string.hello) String myHelloString;//不能设置成私有变量 @StringRes String hello;}
@ColorRes
@EActivitypublic class MyActivity extends Activity { @ColorRes(R.color.backgroundColor) int someColor; @ColorRes int backgroundColor;}
@AnimationRes
@EActivitypublic class MyActivity extends Activity { @AnimationRes(R.anim.fadein) XmlResourceParser xmlResAnim; @AnimationRes Animation fadein;}
@DimensionRes
@EActivitypublic class MyActivity extends Activity { @DimensionRes(R.dimen.fontsize) float fontSizeDimension; @DimensionRes float fontsize;}
@DImensionPixelOffsetRes
@EActivitypublic class MyActivity extends Activity { @DimensionPixelOffsetRes(R.string.fontsize) int fontSizeDimension; @DimensionPixelOffsetRes int fontsize;}
@DimensionPixelSizeRes
@EActivitypublic class MyActivity extends Activity { @DimensionPixelSizeRes(R.string.fontsize) int fontSizeDimension; @DimensionPixelSizeRes int fontsize;}
其他的Res:
@BooleanRes
@ColorStateListRes
@DrawableRes
@IntArrayRes
@IntegerRes
@LayoutRes
@MovieRes
@TextRes
@TextArrayRes
@StringArrayRes
@Extra
@EActivitypublic class MyActivity extends Activity { @Extra(myStringExtra) String myMessage; @Extra(myDateExtra) Date myDateExtraWithDefaultValue = new Date();}
或者:
@EActivitypublic class MyActivity extends Activity { // The name of the extra will be myMessage,名字必须一致 @Extra String myMessage;}
传值:
MyActivity_.intent().myMessage(hello).start() ;
@SystemService
@EActivitypublic class MyActivity extends Activity {// @SystemService NotificationManager notificationManager;}
@HtmlRes
@EActivitypublic class MyActivity extends Activity { // Injects R.string.hello_html @HtmlRes(R.string.hello_html) Spanned myHelloString; // Also injects R.string.hello_html @HtmlRes CharSequence helloHtml;}
@FromHtml
@EActivitypublic class MyActivity extends Activity {//必须用在TextView @ViewById(R.id.my_text_view) @FromHtml(R.string.hello_html) TextView textView; // Injects R.string.hello_html into the R.id.hello_html view @ViewById @FromHtml TextView helloHtml;}
@NonConfigurationInstance
public class MyActivity extends Activity {//等同于 Activity.onRetainNonConfigurationInstance() @NonConfigurationInstance Bitmap someBitmap; @NonConfigurationInstance @Bean MyBackgroundTask myBackgroundTask;}
@HttpsClient
@HttpsClient HttpClient httpsClient;
示例:
@EActivitypublic class MyActivity extends Activity { @HttpsClient(trustStore=R.raw.cacerts, trustStorePwd=changeit, hostnameVerif=true) HttpClient httpsClient; @AfterInject @Background public void securedRequest() { try {HttpGet httpget = new HttpGet(www.verisign/);HttpResponse response = httpsClient.execute(httpget);doSomethingWithResponse(response); } catch (Exception e) {e.printStackTrace(); } } @UiThread public void doSomethingWithResponse(HttpResponse resp) { Toast.makeText(this, HTTP status + resp.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show(); }}
@FragmentArg
@EFragmentpublic class MyFragment extends Fragment {//等同于 Fragment Argument @FragmentArg(myStringArgument) String myMessage; @FragmentArg String anotherStringArgument; @FragmentArg(myDateExtra) Date myDateArgumentWithDefaultValue = new Date();}
MyFragment myFragment = MyFragment_.builder() .myMessage(Hello) .anotherStringArgument(World) .build();
@Click
@Click(R.id.myButton)void myButtonWasClicked() { [...]}@Clickvoid anotherButton() {//如果不指定则函数名和id对应 [...]}@Clickvoid yetAnotherButton(View clickedView) { [...]}
其他点击事件:
Clicks with @Click
Long clicks with @LongClick
Touches with @Touch
AdapterViewEvents
Item clicks with @ItemClick
Long item clicks with @ItemLongClick
Item selection with @ItemSelect 有两种方式调用: 1.
@EActivity(R.layout.my_list)public class MyListActivity extends Activity { // ... @ItemClick public void myListItemClicked(MyItem clickedItem) {//MyItem是adapter的实体类,等同于adapter.getItem(position) } @ItemLongClick public void myListItemLongClicked(MyItem clickedItem) { } @ItemSelect public void myListItemSelected(boolean selected, MyItem selectedItem) { }}2.
@EActivity(R.layout.my_list)public class MyListActivity extends Activity { // ... @ItemClick public void myListItemClicked(int position) {//位置id } @ItemLongClick public void myListItemLongClicked(int position) { } @ItemSelect public void myListItemSelected(boolean selected, int position) { }}
@SeekBarProgressChange
//等同于SeekBar.OnSeekBarChangeListener.onProgressChanged(SeekBar, int, boolean)
@SeekBarProgressChange(R.id.seekBar) void onProgressChangeOnSeekBar(SeekBar seekBar, int progress, boolean fromUser) { // Something Here } @SeekBarProgressChange(R.id.seekBar) void onProgressChangeOnSeekBar(SeekBar seekBar, int progress) { // Something Here } @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2}) void onProgressChangeOnSeekBar(SeekBar seekBar) { // Something Here } @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2}) void onProgressChangeOnSeekBar() { // Something Here }@SeekBarTouchStart and @SeekBarTouchStop
@SeekBarTouchStart 和 @SeekBarTouchStop接受开始和结束事件的监听
@TextChange
@TextChange(R.id.helloTextView) void onTextChangesOnHelloTextView(CharSequence text, TextView hello, int before, int start, int count) { // Something Here } @TextChange void helloTextViewTextChanged(TextView hello) { // Something Here } @TextChange({R.id.editText, R.id.helloTextView}) void onTextChangesOnSomeTextViews(TextView tv, CharSequence text) { // Something Here } @TextChange(R.id.helloTextView) void onTextChangesOnHelloTextView() { // Something Here }
@BeforeTextChange
@BeforeTextChange(R.id.helloTextView) void beforeTextChangedOnHelloTextView(TextView hello, CharSequence text, int start, int count, int after) { // Something Here } @BeforeTextChange void helloTextViewBeforeTextChanged(TextView hello) { // Something Here } @BeforeTextChange({R.id.editText, R.id.helloTextView}) void beforeTextChangedOnSomeTextViews(TextView tv, CharSequence text) { // Something Here } @BeforeTextChange(R.id.helloTextView) void beforeTextChangedOnHelloTextView() { // Something Here }
@AfterTextChange
@AfterTextChange(R.id.helloTextView) void afterTextChangedOnHelloTextView(Editable text, TextView hello) { // Something Here } @AfterTextChange void helloTextViewAfterTextChanged(TextView hello) { // Something Here } @AfterTextChange({R.id.editText, R.id.helloTextView}) void afterTextChangedOnSomeTextViews(TextView tv, Editable text) { // Something Here } @AfterTextChange(R.id.helloTextView) void afterTextChangedOnHelloTextView() { // Something Here }
@OptionsMenu和OptionsItem
@EActivity@OptionsMenu(R.menu.my_menu)public class MyActivity extends Activity { @OptionMenuItem MenuItem menuSearch; @OptionsItem(R.id.menuShare) void myMethod() { // You can specify the ID in the annotation, or use the naming convention } @OptionsItem void homeSelected() {// home was selected in the action bar // The Selected keyword is optional } @OptionsItem boolean menuSearch() { menuSearch.setVisible(false); // menuSearch was selected // the return type may be void or boolean (false to allow normal menu processing to proceed, true to consume it here) return true; } @OptionsItem({ R.id.menu_search, R.id.menu_delete }) void multipleMenuItems() {// You can specify multiple menu item IDs in @OptionsItem } @OptionsItem void menu_add(MenuItem item) {// You can add a MenuItem parameter to access it }}
或者:
@EActivity@OptionsMenu({R.menu.my_menu1, R.menu.my_menu2})public class MyActivity extends Activity {}
@Background执行:
void myMethod() { someBackgroundWork(hello, 42);}@Backgroundvoid someBackgroundWork(String aParam, long anotherParam) { [...]}
取消:
void myMethod() { someCancellableBackground(hello, 42); [...] boolean mayInterruptIfRunning = true; BackgroundExecutor.cancelAll(cancellable_task, mayInterruptIfRunning);}@Background(id=cancellable_task)void someCancellableBackground(String aParam, long anotherParam) { [...]}
非并发执行:
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);}
延迟:
@Background(delay=2000)void doInBackgroundAfterTwoSeconds() {}
@UiThreadUI线程:
void myMethod() { doInUiThread(hello, 42);}@UiThreadvoid doInUiThread(String aParam, long anotherParam) { [...]}
延迟:
@UiThread(delay=2000)void doInUiThreadAfterTwoSeconds() {}
优化UI线程:
@UiThread(propagation = Propagation.REUSE)void runInSameThreadIfOnUiThread() {}
进度值改变:
@EActivitypublic class MyActivity extends Activity { @Background void doSomeStuffInBackground() { publishProgress(0); // Do some stuff publishProgress(10); // Do some stuff publishProgress(100); } @UiThread void publishProgress(int progress) { // Update progress views }}
@OnActivityResult
@OnActivityResult(REQUEST_CODE) void onResult(int resultCode, Intent data) { } @OnActivityResult(REQUEST_CODE) void onResult(int resultCode) { } @OnActivityResult(ANOTHER_REQUEST_CODE) void onResult(Intent data) { } @OnActivityResult(ANOTHER_REQUEST_CODE) void onResult() { }
更多推荐
Android实战开发基础框架搭建
发布评论