xUtils3.0框架学习笔记分享
xutils是开速开发安卓项目的开源框架,开源项目地址:https://github.com/wyouflf/xutils3。使用起来非常方便。主要功能包括:
1、xutils 支持超大文件(超过2g)上传,更全面的http请求协议支持(11种谓词)。
2、拥有更加灵活的orm,更多的事件注解支持且不受混淆影响。
3、图片绑定支持gif(受系统兼容性影响, 部分gif文件只能静态显示), webp; 支持圆角, 圆形, 方形等裁剪, 支持自动旋转等。
4、数据库api简化提高性能, 达到和greendao一致的性能。
5、http实现替换httpclient为urlconnection, 自动解析回调泛型, 更安全的断点续传策略等。
控件及事件注解绑定,方便高效http请求,简单地数据库操作方式,确实是一款非常有助于我们快速开发项目的开源框架。
参考github上面demo及相关资料,写了一个学习的demo,分别从注解,图片,http及数据库四个方面进行了代码编写。
首先是在androidstudio中配置项目:
第一步:
在androidstudio项目的build.gradle文件中添加compile ‘org.xutils:xutils:3.3.36':
dependencies { compile filetree(dir: 'libs', include: ['*.jar']) testcompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'org.xutils:xutils:3.3.36' }
添加好后build下工程即可。
第二步:
在androidmanifest.xml中添加对应权限:
<uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.write_external_storage" />
第三步:在项目中自定义application,初始化xutils3.0。
/** * description: * 作者:ldm * 时间:20162016/6/22 09:03 * 邮箱:1786911211@qq.com */ public class baseapplication extends application { @override public void oncreate() { super.oncreate(); x.ext.init(this);//在自定义的application中初始化xutils3.0 } }
记得把我们定义的application配置到androidmanifest.xml中。
接下来就可以作用xutils3.0进行快速开发了。
—– 第一部分:注解示例—–
/** * description:xutils3.0框架注解功能 * 作者:ldm * 时间:20162016/6/22 09:17 * 邮箱:1786911211@qq.com */ @contentview(r.layout.activity_annotation) public class annotationactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); x.view().inject(this); fragmentmanager fragmentmanager = getfragmentmanager(); fragmenttransaction fragmenttransaction = fragmentmanager.begintransaction(); testfragment fragment = new testfragment(); fragmenttransaction.add(r.id.fra_layout, fragment); fragmenttransaction.commit(); } }
—–注解功能对应地fragment—–
/** * description:xutils3.0框架注解之:fragment中注解使用 * 作者:ldm * 时间:20162016/6/22 09:28 * 邮箱:1786911211@qq.com */ @contentview(r.layout.frag_test)//给fragment绑定布局文件 public class testfragment extends fragment { @viewinject(r.id.test_listview) private listview listview; private list<listbean> datas; public testfragment() { super(); } @nullable @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { return x.view().inject(this, inflater, container);//调用x.view().inject()方法返回view } //oncreateview是创建的时候调用,onviewcreated是在oncreateview后被触发的事件 @override public void onviewcreated(view view, @nullable bundle savedinstancestate) { super.onviewcreated(view, savedinstancestate); constructdatas(); listview.setadapter(new testadapter(getactivity(), datas)); } private void constructdatas() { datas = new arraylist<>(); for (int i = 0; i < 15; i++) { listbean bean = new listbean("这是第" + i + "个标题", "这里都是相同的内容"); datas.add(bean); } } //listview的item点击事件注解操作 @event(type = adapterview.onitemclicklistener.class, value = r.id.test_listview) private void onitemclick(adapterview<?> parent, view view, int position, long id) { toast.maketext(getactivity(), "点击了第" + position + "个item", toast.length_long).show(); } //长按事件注解操作 @event(type = adapterview.onitemlongclicklistener.class, value = r.id.test_listview) private boolean onlongitemclick(adapterview<?> parent, view view, int position, long id) { toast.maketext(getactivity(), "长按第" + position + "个item", toast.length_long).show(); return true; } }
—–第二部分:图片加载示例—–
/** * description:xutils3.0框架图片功能 * 作者:ldm * 时间:20162016/6/22 09:17 * 邮箱:1786911211@qq.com */ @contentview(r.layout.activity_image) public class imageactivity extends activity { @viewinject(r.id.image_01) private imageview image_01; @viewinject(r.id.image_02) private imageview image_02; @viewinject(r.id.image_03) private imageview image_03; @viewinject(r.id.image_04) private imageview image_04; private string url_01 = ""; private string url_02 = ""; private string url_03 = ""; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); x.view().inject(this);//需要添加这句代码,否则不会关联到布局 } //加载网络图片第一种方法 @event(value = r.id.image_01) private void loadimagemethodone(view v) { //直接调用 bind(imageview view, string url)方法,传入对应控件及url即可 x.image().bind(image_01, url_01); } //加载网络图片第二种方法 @event(value = r.id.image_02) private void loadimagemethodtwo(view v) { //创建图片参数设置类imageoptions imageoptions options = new imageoptions.builder().build(); //直接调用bind(imageview view, string url, imageoptions options)方法,传入对应参数 x.image().bind(image_02, url_02, options); } //加载网络图片第三种方法 @event(value = r.id.image_03) private void loadimagemethodthree(view v) { //调用bind(imageview view, string url, callback.commoncallback<drawable> callback) x.image().bind(image_03, url_03, new callback.cachecallback<drawable>() { @override public boolean oncache(drawable result) {//可以在这里设置图片保存等操作 return false; } @override public void onsuccess(drawable result) {//获取成功 } @override public void onerror(throwable ex, boolean isoncallback) {//获取失败 } @override public void oncancelled(cancelledexception cex) {//取消操作 } @override public void onfinished() {//完成操作 } }); } //加载本地图片 @event(value = r.id.image_04) private void loadimagemethodfour(view v) { imageoptions options = new imageoptions.builder(). setimagescaletype(imageview.scaletype.fit_center). setusememcache(true). build();//可以设置options各项参数 // assets下的图片 // x.image().bind(image_04, "assets://test.png", options); // sd卡下图片 // x.image().bind(image_04, new file("/sdcard/test.png").touri().tostring(), options); x.image().bind(image_04, "/sdcard/test.gif", options); } }
—–第三部分:http请求—–
/** * description:xutils框架之http请求 * 作者:ldm * 时间:20162016/6/22 09:17 * 邮箱:1786911211@qq.com */ @contentview(r.layout.activity_http) public class httpactivity extends activity { @viewinject(r.id.get) private button get; @viewinject(r.id.post) private button post; @viewinject(r.id.upload) private button upload; @viewinject(r.id.download) private button download; private static final string tag = "httpactivity"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); x.view().inject(this); } //http请求之get请求 @event(type = view.onclicklistener.class, value = r.id.get) private void httpgetonclick(view v) { string url = "http://www.baidu.com"; final progressdialog dia = new progressdialog(this); dia.setmessage("加载中...."); dia.show(); requestparams params = new requestparams(url); x.http().get(params, new callback.commoncallback<string>() { @override public void onsuccess(string result) { //加载成功回调,返回获取到的数据 log.i(tag, "onsuccess: " + result); } @override public void onfinished() { dia.dismiss();//加载完成 } @override public void oncancelled(cancelledexception cex) { } @override public void onerror(throwable ex, boolean isoncallback) { } }); } //http请求之post请求 @event(type = view.onclicklistener.class, value = r.id.post) private void httppostonclick(view v) { string url = "this is request url for post"; final progressdialog dia = new progressdialog(this); dia.setmessage("加载中...."); dia.show(); requestparams params = new requestparams(url); params.addparameter("username", "admin");//添加post请求参数,如果是get请求,会直接添加到url后面 params.addbodyparameter("password", "123456"); params.addheader("head", "给head添加信息");//addheader添加head信息 x.http().post(params, new callback.commoncallback<string>() { @override public void onsuccess(string result) { //加载成功回调,返回获取到的数据 log.i(tag, "onsuccess: " + result); } @override public void onfinished() { dia.dismiss();//加载完成 } @override public void oncancelled(cancelledexception cex) { } @override public void onerror(throwable ex, boolean isoncallback) { } }); } //http请求之文件上传 @event(type = view.onclicklistener.class, value = r.id.upload) private void uploadonclick(view v) { string upurl = "/mnt/sdcard/pic/test.jpg";//指定要上传的文件 final progressdialog dia = new progressdialog(this); dia.setmessage("加载中...."); dia.show(); requestparams params = new requestparams(upurl); params.addbodyparameter("file", new file(upurl)); x.http().post(params, new callback.commoncallback<string>() { @override public void onsuccess(string result) { //加载成功回调,返回获取到的数据 log.i(tag, "onsuccess: " + result); } @override public void onfinished() { dia.dismiss();//加载完成 } @override public void oncancelled(cancelledexception cex) { } @override public void onerror(throwable ex, boolean isoncallback) { } }); } //http请求之文件下载 @event(type = view.onclicklistener.class, value = r.id.download) private void downloadonclick(view v) { string downurl = "please input download url"; final progressdialog dia = new progressdialog(this); dia.setmessage("加载中...."); dia.show(); requestparams params = new requestparams(downurl); x.http().post(params, new callback.commoncallback<file>() { @override public void onsuccess(file result) { //下载成功 intent in = new intent(intent.action_view); in.setdataandtype(uri.fromfile(result), "application/vnd.android.package-archive");//比如我们下载的apk文件,直接安装 startactivity(in); } @override public void onfinished() { dia.dismiss(); } @override public void oncancelled(cancelledexception cex) { } @override public void onerror(throwable ex, boolean isoncallback) { } }); } }
—-第四部分:数据库操作——
/** * description:xutils3.0框架数据库操作 * 作者:ldm * 时间:20162016/6/22 09:17 * 邮箱:1786911211@qq.com */ @contentview(r.layout.activity_db) public class databaseactivity extends activity { @viewinject(r.id.create) private button create; @viewinject(r.id.add) private button add; @viewinject(r.id.delete) private button delete; @viewinject(r.id.query) private button query; @viewinject(r.id.update) private button update; @viewinject(r.id.del_db) private button del_db; private dbmanager.daoconfig daoconfig; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); x.view().inject(this); } private void initdatabase() { daoconfig = new dbmanager.daoconfig() .setdbname("test.db")//数据库名称 // 不设置dbdir时, 默认存储在app的私有目录. .setdbdir(new file("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了. .setdbversion(2)//设置版本号 .setdbopenlistener(new dbmanager.dbopenlistener() { @override public void ondbopened(dbmanager db) { // 开启wal, 对写入加速提升巨大 db.getdatabase().enablewriteaheadlogging(); } }) .setdbupgradelistener(new dbmanager.dbupgradelistener() {//数据库升级 @override public void onupgrade(dbmanager db, int oldversion, int newversion) { // todo: ... // db.addcolumn(...); // db.droptable(...); // ... // or // db.dropdb(); } }); } //创建数据库及表格 @event(value = r.id.create) private void createonclick(view v) throws exception { initdatabase(); dbmanager db = x.getdb(daoconfig); teacher t = new teacher("张三", 28, "english", 1); db.save(t);//调用这句话,则可以创建表格,并把数据存入 } //添加数据 @event(value = r.id.add) private void addonclick(view v) throws exception { dbmanager db = x.getdb(daoconfig); teacher t = new teacher("李四", 38, "math", 3); db.save(t);//如果表格存在,并把数据存入 list<teacher> list = new arraylist<>(); list.add(new teacher("王五", 30, "engilsh", 2)); list.add(new teacher("赵六", 40, "chinese", 3)); list.add(new teacher("陈七", 50, "math", 4)); db.save(list);//可以这样保存多条数据到指定表格 } //删除数据 @event(value = r.id.delete) private void deleteonclick(view v) throws exception { dbmanager db = x.getdb(daoconfig); wherebuilder wb = wherebuilder.b(); wb.and("level", "=", 1); db.delete(teacher.class, wb);//删除等级为1的教师 } //修改数据 @event(value = r.id.update) private void updateonclick(view v) throws exception { dbmanager db = x.getdb(daoconfig); db.update(teacher.class, wherebuilder.b().and("name", "=", "王五"), new keyvalue("name", "朱八"));//把王五的名字改成朱八 } //查询数据 @event(value = r.id.query) private void queryonclick(view v) throws exception { dbmanager db = x.getdb(daoconfig); wherebuilder wb = wherebuilder.b(); wb.and("level", "=", 2); list<teacher> list = db.selector(teacher.class).findall();//查询所有数据 list<teacher> list1 = db.selector(teacher.class).where(wb).findall();//查询等级数2的教师 } //删除数据库或表格 @event(value = r.id.del_db) private void deldbonclick(view v) throws exception { dbmanager db = x.getdb(daoconfig); db.dropdb();//删除数据库 db.droptable(teacher.class);//删除teacher表格 } }
由于时间关系,代码写得比较粗糙,后期使用中再细化。
demo下载地址:http://xiazai.jb51.net/201611/yuanma/xutilsdemo(jb51.net).rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。