xUtils简介以及使用方法

  还在为开发新项目而加班加点吗?还在为莫个功能重复制造轮子吗?今天为给你介绍一个开源的项目xUtils
为你快速开发项目,提供神器。

   以下内容全部来自README文件。
##xUtils简介
*xUtils 包含了很多实用的android工具。
*xUtils最初源于Afinal框架,进行了大量重构,使得xUtils支持大文件上传,更全面的http请求协议支持(10种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响...
*xUitls最低兼容android2.2 (api level 8)
##目前xUtils主要有四大模块:
*DbUtils模块:
  >* android中的orm框架,一行代码就可以进行增删改查;
  >* 支持事务,默认关闭;
  >* 可通过注解自定义表名,列名,外键,唯一性约束,NOTNULL约束,CHECK约束等(需要混淆的时候请注解表名和列名);
  >* 支持绑定外键,保存实体时外键关联实体自动保存或更新;
  >* 自动加载外键关联实体,支持延时加载;
  >* 支持链式表达查询,更直观的查询语义,参考下面的介绍或sample中的例子。
*ViewUtils模块:
  >* android中的ioc框架,完全注解方式就可以进行UI,资源和事件绑定;
  >* 新的事件绑定方式,使用混淆工具混淆后仍可正常工作;
  >*目前支持常用的20种事件绑定,参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event
*HttpUtils模块:
  >* 支持同步,异步方式的请求;
  >* 支持大文件上传,上传大文件不会oom
  >* 支持GETPOSTPUTMOVECOPYDELETEHEADOPTIONSTRACECONNECT请求;
  >* 下载支持301/302重定向,支持设置是否根据Content-Disposition重命名下载的文件;
  >* 返回文本内容的请求(默认只启用了GET请求)支持缓存,可设置默认过期时间和针对当前请求的过期时间。
*BitmapUtils模块:
  >* 加载bitmap的时候无需考虑bitmap加载过程中出现的oomandroid容器快速滑动时候出现的图片错位等现象;
  >* 支持加载网络图片和本地图片;
  >* 内存管理使用lru算法,更好的管理bitmap内存;
  >* 可配置线程加载线程数量,缓存大小,缓存路径,加载显示动画等...
----
##使用xUtils快速开发框架需要有以下权限:
```xml
<uses-permissionandroid:name="android.permission.INTERNET" />
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
----
##混淆时注意事项:
*添加Android默认混淆配置${sdk.dir}/tools/proguard/proguard-android.txt
*不要混淆xUtils中的注解类型,添加混淆配置:-keepclass * extends java.lang.annotation.Annotation { *; }
*对使用DbUtils模块持久化的实体类不要混淆,或者注解所有表和列名称@Table(name="xxx")@Id(column="xxx")@Column(column="xxx"),@Foreign(column="xxx",foreign="xxx")
----
##DbUtils使用方法:
```java
  1. DbUtilsdb = DbUtils.create(this);
  2. Useruser = new User(); //这里需要注意的是User对象必须有id属性,或者有通过@ID注解的属性
  3. user.setEmail("[email protected]");
  4. user.setName("wyouflf");
  5. db.save(user);// 使用saveBindingId保存实体时会为实体的id赋值
复制代码


...
//查找
  1. Parententity = db.findById(Parent.class, parent.getId());
  2. Parententity = db.findFirst(entity);//通过entity的属性查找
  3. List<Parent>list = db.findAll(entity);//通过entity的属性查找
  4. List<Parent>list = db.findAll(Parent.class);//通过类型查找
  5. ParentParent =db.findFirst(Selector.from(Parent.class).where("name","=","test"));
  6. //IS NULL
  7. ParentParent = db.findFirst(Selector.from(Parent.class).where("name","=",null));
  8. //IS NOT NULL
  9. ParentParent = db.findFirst(Selector.from(Parent.class).where("name","!=",null));
  10. //WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMITpageSize OFFSET pageOffset
  11. List<Parent>list = db.findAll(Selector.from(Parent.class)
  12.                                   .where("id","<", 54)
  13.                                   .and(WhereBuilder.b("age",">", 20).or("age", " < ", 30))
  14.                                   .orderBy("id")
  15.                                   .limit(pageSize)
  16.                                   .offset(pageSize* pageIndex));
  17. //op为"in"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
  18. Parenttest = db.findFirst(Selector.from(Parent.class).where("id","in", new int[]{1, 2, 3}));
  19. //op为"between"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
  20. Parenttest = db.findFirst(Selector.from(Parent.class).where("id","between", new String[]{"1", "5"}));
  21. DbModeldbModel =db.findDbModelAll(Selector.from(Parent.class).select("name"));//select("name")只取出name列
  22. List<DbModel>dbModels =db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name","count(name)"));
  23. ...
  24. List<DbModel>dbModels = db.findDbModelAll(sql); // 自定义sql查询
  25. db.execNonQuery(sql)// 执行自定义sql
复制代码


...
```
----
##ViewUtils使用方法
*完全注解方式就可以进行UI绑定和事件绑定。
*无需findViewByIdsetClickListener等。
```java
  1. //xUtils的view注解要求必须提供id,以使代码混淆不受影响。
  2. @ViewInject(R.id.textView)
  3. TextViewtextView;
  4. //@ViewInject(vale=R.id.textView,parentId=R.id.parentView)
  5. //TextViewtextView;
  6. @ResInject(id= R.string.label, type = ResType.String)
  7. privateString label;
  8. //取消了之前使用方法名绑定事件的方式,使用id绑定不受混淆影响
  9. //支持绑定多个id@OnClick({R.id.id1, R.id.id2, R.id.id3})
  10. //or @OnClick(value={R.id.id1, R.id.id2, R.id.id3},parentId={R.id.pid1, R.id.pid2, R.id.pid3})
  11. //更多事件支持参见ViewCommonEventListener类和包com.lidroid.xutils.view.annotation.event。
  12. @OnClick(R.id.test_button)
  13. publicvoid testButtonClick(View v) { // 方法签名必须和接口中的要求一致
  14.     ...
  15. }
  16. ...
  17. //在Activity中注入:
  18. @Override
  19. publicvoid onCreate(Bundle savedInstanceState) {
  20.    super.onCreate(savedInstanceState);
  21.    setContentView(R.layout.main);
  22.    ViewUtils.inject(this);//注入view和事件
  23.     ...
  24.    textView.setText("sometext...");
  25.     ...
  26. }
  27. //在Fragment中注入:
  28. @Override
  29. publicView onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
  30.     Viewview = inflater.inflate(R.layout.bitmap_fragment, container, false);// 加载fragment布局
  31.    ViewUtils.inject(this,view); //注入view和事件
  32.     ...
  33. }
  34. //在PreferenceFragment中注入:
  35. publicvoid onActivityCreated(Bundle savedInstanceState) {
  36.    super.onActivityCreated(savedInstanceState);
  37.    ViewUtils.inject(this,getPreferenceScreen()); //注入view和事件
  38.     ...
  39. }
  40. //其他重载
  41. //inject(View view);
  42. //inject(Activity activity)
  43. //inject(PreferenceActivity preferenceActivity)
  44. //inject(Object handler, View view)
  45. //inject(Object handler, Activity activity)
  46. //inject(Object handler, PreferenceGroup preferenceGroup)
  47. //inject(Object handler, PreferenceActivity preferenceActivity)
复制代码


```
----
##HttpUtils使用方法:
###普通get方法
```java
  1. HttpUtilshttp = new HttpUtils();
  2. http.send(HttpRequest.HttpMethod.GET,
  3.    "http://www.lidroid.com",
  4.     newRequestCallBack<String>(){
  5.        @Override
  6.         publicvoid onLoading(long total, long current, boolean isUploading) {
  7.            testTextView.setText(current+ "/" + total);
  8.         }
  9.        @Override
  10.         publicvoid onSuccess(ResponseInfo<String> responseInfo) {
  11.            textView.setText(responseInfo.result);
  12.         }
  13.        @Override
  14.         publicvoid onStart() {
  15.         }
  16.        @Override
  17.         publicvoid onFailure(HttpException error, String msg) {
  18.         }
  19. });
复制代码


```
----
###使用HttpUtils上传文件或者 提交数据 到服务器(post方法)
```java
  1. RequestParamsparams = new RequestParams();
  2. params.addHeader("name","value");
  3. params.addQueryStringParameter("name","value");
  4. //只包含字符串参数时默认使用BodyParamsEntity,
  5. //类似于UrlEncodedFormEntity("application/x-www-form-urlencoded")。
  6. params.addBodyParameter("name","value");
  7. //加入文件参数后默认使用MultipartEntity("multipart/form-data"),
  8. //如需"multipart/related",xUtils中提供的MultipartEntity支持设置subType为"related"。
  9. //使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity(如:
  10. //MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity)。
  11. //例如发送json参数:params.setBodyEntity(newStringEntity(jsonStr,charset));
  12. params.addBodyParameter("file",new File("path"));
  13. ...
  14. HttpUtilshttp = new HttpUtils();
  15. http.send(HttpRequest.HttpMethod.POST,
  16.    "uploadUrl....",
  17.     params,
  18.     newRequestCallBack<String>() {
  19.        @Override
  20.         publicvoid onStart() {
  21.            testTextView.setText("conn...");
  22.         }
  23.        @Override
  24.         publicvoid onLoading(long total, long current, boolean isUploading) {
  25.             if(isUploading) {
  26.                testTextView.setText("upload:" + current + "/" + total);
  27.             }else {
  28.                testTextView.setText("reply:" + current + "/" + total);
  29.             }
  30.         }
  31.        @Override
  32.         publicvoid onSuccess(ResponseInfo<String> responseInfo) {
  33.            testTextView.setText("reply:" + responseInfo.result);
  34.         }
  35.        @Override
  36.         publicvoid onFailure(HttpException error, String msg) {
  37.            testTextView.setText(error.getExceptionCode()+ ":" + msg);
  38.         }
  39. });
复制代码


```
----
###使用HttpUtils下载文件:
*支持断点续传,随时停止下载任务,开始任务
```java
  1. HttpUtilshttp = new HttpUtils();
  2. HttpHandlerhandler =http.download("http://apache.dataguru.cn/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip",
  3.    "/sdcard/httpcomponents-client-4.2.5-src.zip",
  4.     true,// 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
  5.     true,// 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
  6.     newRequestCallBack<File>() {
  7.        @Override
  8.         publicvoid onStart() {
  9.            testTextView.setText("conn...");
  10.         }
  11.        @Override
  12.         publicvoid onLoading(long total, long current, boolean isUploading) {
  13.            testTextView.setText(current+ "/" + total);
  14.         }
  15.        @Override
  16.         publicvoid onSuccess(ResponseInfo<File> responseInfo) {
  17.            testTextView.setText("downloaded:"+ responseInfo.result.getPath());
  18.         }
  19.        @Override
  20.         publicvoid onFailure(HttpException error, String msg) {
  21.            testTextView.setText(msg);
  22.         }
  23. });
  24. ...
  25. //调用stop()方法停止下载
  26. handler.stop();
复制代码


...
```
----
##BitmapUtils 使用方法
```java
  1. BitmapUtilsbitmapUtils = new BitmapUtils(this);
  2. //加载网络图片
  3. bitmapUtils.display(testImageView,"http://bbs.lidroid.com/static/image/common/logo.png");
  4. //加载本地图片(路径以/开头,绝对路径)
  5. bitmapUtils.display(testImageView,"/sdcard/test.jpg");
  6. //加载assets中的图片(路径以assets开头)
  7. bitmapUtils.display(testImageView,"assets/img/wallpaper.jpg");
  8. //使用ListView等容器展示图片时可通过PauseOnScrollListener控制滑动和快速滑动过程中时候暂停加载图片
  9. listView.setOnScrollListener(newPauseOnScrollListener(bitmapUtils, false, true));
  10. listView.setOnScrollListener(newPauseOnScrollListener(bitmapUtils, false, true, customListener));
复制代码


```
----
##其他(***更多示例代码见sample文件夹中的代码***
###输出日志 LogUtils
```java
  1. //自动添加TAG,格式:className.methodName(L:lineNumber)
  2. //可设置全局的LogUtils.allowD= false,LogUtils.allowI= false...,控制是否输出log。README
  3. //自定义log输出LogUtils.customLogger= new xxxLogger();
  4. LogUtils.d("wyouflf");
复制代码



xUtils简介以及使用方法_第1张图片xUtils简介以及使用方法_第2张图片xUtils简介以及使用方法_第3张图片

Screenshot_2013-12-28-10-43-16.png (21.28 KB, 下载次数: 6)

xUtils简介以及使用方法_第4张图片

你可能感兴趣的:(xUtils简介以及使用方法)