欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

xUtils3.0框架学习笔记分享

时间:2021-02-21 14:56:03|栏目:Android代码|点击:

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进行快速开发了。

―?C 第一部分:注解示例―?C

/**
 * 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();
 }
}

―?C注解功能对应地Fragment―?C

/**
 * 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;
 }
}

―?C第二部分:图片加载示例―?C

/**
 * 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);
 }
}

―?C第三部分:HTTP请求―?C

/**
 * 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

上一篇:Android Studio 3.0上分析内存泄漏的原因

栏    目:Android代码

下一篇:Android ListView分页简单实现

本文标题:xUtils3.0框架学习笔记分享

本文地址:http://www.codeinn.net/misctech/67213.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有