初始化
// 在application的onCreate中初始化/**
* 初始化xUtils3
*/public class MyApp extends Application {
@Override
public void onCreate() { super.onCreate(); //对xUtils进行初始化
x.Ext.init(this); //是否是开发、调试模式
x.Ext.setDebug(BuildConfig.DEBUG);//是否输出debug日志,开启debug会影响性能
}
}
在Manifest文件中注册MyApp
<application
android:name=".MyApp"
android:allowBackup="true"
......
</application>
使用@Event事件注解(@ContentView,@ViewInject等)
xUtils3注解模块在实际开发中的使用如下:
1.Activity的注解的使用如下:
@ContentView(R.layout.activity_main)public class MainActivity extends AppCompatActivity {
@ViewInject(R.id.viewpager)
ViewPager viewPager;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
x.view().inject(this);
...
}
}
2.Fragment的注解的使用如下:
@ContentView(R.layout.fragment_http)public class HttpFragment extends Fragment { @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return x.view().inject(this, inflater, container);
} @Override
public void onViewCreated(View v, @Nullable Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState);
}
}
3.为按钮设置点击事件
@ViewInject(R.id.bt_main)
Button bt_main;
...@Overrideprotected void onCreate(Bundle savedInstanceState) {
...
}/**
* 用注解的方式为按钮添加点击事件,方法声明必须为private
* type默认View.OnClickListener.class,故此处可以简化不写,@Event(R.id.bt_main)
*/@Event(type = View.OnClickListener.class,value = R.id.bt_main)private void testInjectOnClick(View v){
Snackbar.make(v,"OnClickListener",Snackbar.LENGTH_SHORT).show();
}/**
* 长按事件
*/@Event(type = View.OnLongClickListener.class,value = R.id.bt_main)private boolean testOnLongClickListener(View v){
Snackbar.make(v,"testOnLongClickListener",Snackbar.LENGTH_SHORT).show(); return true;
}
xUtils3网络模块的使用
xUtils3网络模块大大方便了在实际开发中网络模块的开发,xUtils3网络模块大致包括GET请求、POST请求、如何使用其他请求方式、上传文件、下载文件、使用缓存等功能。
1.GET请求
String url = "http://www.baidu.com";
@Event(R.id.get)private void get(View v){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("请稍候...");
RequestParams params = new RequestParams(url);
params.addQueryStringParameter("username","abc");
params.addQueryStringParameter("password","123");
Callback.Cancelable cancelable = x.http().get(params, new Callback.CommonCallback() {
@Override public void onSuccess(String result) {
Log.i("JAVA", "onSuccess result:" + result);
progressDialog.cancel();
} //请求异常后的回调方法
@Override public void onError(Throwable ex, boolean isOnCallback) {
} //主动调用取消请求的回调方法
@Override public void onCancelled(CancelledException cex) {
}
@Override public void onFinished() {
progressDialog.cancel();
}
}); //主动调用取消请求
cancelable.cancel();
}
2.POST请求
String url = "http://www.baidu.com";@Event(R.id.post)private void post(View v){
RequestParams params = new RequestParams(url);
params.addBodyParameter("username","abc");
params.addParameter("password","123");
params.addHeader("head","android"); //为当前请求添加一个头
x.http().post(params, new Callback.CommonCallback() { @Override
public void onSuccess(String result) {
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
}
3.其他网络请求方式
String url = "http://www.baidu.com";@Event(R.id.other)private void other(View v){
RequestParams params = new RequestParams(url);
params.addParameter("username","abc");
x.http().request(HttpMethod.PUT, params, new Callback.CommonCallback() { @Override
public void onSuccess(String result) {
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
}
4.上传文件
String url = "http://www.baidu.com";@Event(R.id.upload)private void upload(View v){
String path="/mnt/sdcard/Download/icon.jpg";
RequestParams params = new RequestParams(url);
params.setMultipart(true);
params.addBodyParameter("file",new File(path));
x.http().post(params, new Callback.CommonCallback() { @Override
public void onSuccess(String result) {
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
}
5.下载文件
String url = "http://www.baidu.com";@Event(R.id.download)private void download(View v){
url = "http://127.0.0.1/server/ABC.apk";
RequestParams params = new RequestParams(url); //自定义保存路径,Environment.getExternalStorageDirectory():SD卡的根目录
params.setSaveFilePath(Environment.getExternalStorageDirectory()+"/myapp/"); //自动为文件命名
params.setAutoRename(true);
x.http().post(params, new Callback.ProgressCallback() { @Override
public void onSuccess(File result) { //apk下载完成后,调用系统的安装方法
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
getActivity().startActivity(intent);
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
} //网络请求之前回调
@Override
public void onWaiting() {
} //网络请求开始的时候回调
@Override
public void onStarted() {
} //下载的时候不断回调的方法
@Override
public void onLoading(long total, long current, boolean isDownloading) { //当前进度和文件总大小
Log.i("JAVA","current:"+ current +",total:"+total);
}
});
}
6.使用缓存
String url = "http://www.baidu.com";@Event(R.id.cache)private void cache(View v) {
RequestParams params = new RequestParams(url);
params.setCacheMaxAge(1000*60); //为请求添加缓存时间
Callback.Cancelable cancelable = x.http().get(params, new Callback.CacheCallback() { @Override
public void onSuccess(String result) {
Log.i("JAVA","onSuccess:"+result);
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
} //result:缓存内容
@Override
public boolean onCache(String result) { //在setCacheMaxAge设置范围(上面设置的是60秒)内,如果再次调用GET请求,
//返回true:缓存内容被返回,相信本地缓存,返回false:缓存内容被返回,不相信本地缓存,仍然会请求网络
Log.i("JAVA","cache:"+result); return true;
}
});
}
xUtils图片模块的使用
xUtils3图片模块,重点在于加载图片的4个bind方法,loadDrawable与loadFIle用法和ImageOptions用法。
1.获取ImageView控件
@ViewInject(R.id.image01)ImageView image01;@ViewInject(R.id.image02)ImageView image02;@ViewInject(R.id.image03)ImageView image03;
2.获取网络图片的地址
String[] urls={ "http://img.android.com/a.jpg", "http://img.android.com/b.jpg"
"http://img.android.com/c.jpg"
...
};
3.xUtils3显示图片方法setPic()如下:
private void setPic() { /**
* 通过ImageOptions.Builder().set方法设置图片的属性
*/
ImageOptions options = new ImageOptions.Builder().setFadeIn(true).build(); //淡入效果
//ImageOptions.Builder()的一些其他属性:
//.setCircular(true) //设置图片显示为圆形
//.setSquare(true) //设置图片显示为正方形
//setCrop(true).setSize(200,200) //设置大小
//.setAnimation(animation) //设置动画
//.setFailureDrawable(Drawable failureDrawable) //设置加载失败的动画
//.setFailureDrawableId(int failureDrawable) //以资源id设置加载失败的动画
//.setLoadingDrawable(Drawable loadingDrawable) //设置加载中的动画
//.setLoadingDrawableId(int loadingDrawable) //以资源id设置加载中的动画
//.setIgnoreGif(false) //忽略Gif图片
//.setParamsBuilder(ParamsBuilder paramsBuilder) //在网络请求中添加一些参数
//.setRaduis(int raduis) //设置拐角弧度
//.setUseMemCache(true) //设置使用MemCache,默认true
/**
* 加载图片的4个bind方法
*/
x.image().bind(image01, urls[0]);
x.image().bind(image02, urls[1], options);
x.image().bind(image03, urls[2], options, new Callback.CommonCallback() { @Override
public void onSuccess(Drawable result) {
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
x.image().bind(image04, urls[3], options, new Callback.CommonCallback() { @Override
public void onSuccess(Drawable result) {
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
/**
* loadDrawable()方法加载图片
*/
Callback.Cancelable cancelable = x.image().loadDrawable(urls[0], options, new Callback.CommonCallback() { @Override
public void onSuccess(Drawable result) {
image03.setImageDrawable(result);
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
}); //主动取消loadDrawable()方法
//cancelable.cancel();
/**
* loadFile()方法
* 应用场景:当我们通过bind()或者loadDrawable()方法加载了一张图片后,
* 它会保存到本地文件中,那当我需要这张图片时,就可以通过loadFile()方法进行查找。
* urls[0]:网络地址
*/
x.image().loadFile(urls[0],options,new Callback.CacheCallback(){ @Override
public boolean onCache(File result) { //在这里可以做图片另存为等操作
Log.i("JAVA","file:"+result.getPath()+result.getName()); return true; //相信本地缓存返回true
} @Override
public void onSuccess(File result) {
Log.i("JAVA","file");
} @Override
public void onError(Throwable ex, boolean isOnCallback) {
} @Override
public void onCancelled(CancelledException cex) {
} @Override
public void onFinished() {
}
});
}
xUtils3数据库模块的使用
1.创建数据库和删除数据库
首先进行配置DaoConfig:
/**
* DaoConfig配置
* /
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
//设置数据库名,默认xutils.db
.setDbName("myapp.db")
//设置表创建的监听
.setTableCreateListener(new DbManager.TableCreateListener() { @Override
public void onTableCreated(DbManager db, TableEntity table){
Log.i("JAVA", "onTableCreated:" + table.getName());
}
})
//设置是否允许事务,默认true
//.setAllowTransaction(true)
//设置数据库路径,默认安装程序路径下
//.setDbDir(new File("/mnt/sdcard/"))
//设置数据库的版本号
//.setDbVersion(1)
//设置数据库更新的监听
.setDbUpgradeListener(new DbManager.DbUpgradeListener() { @Override
public void onUpgrade(DbManager db, int oldVersion,
int newVersion) {
}
})
//设置数据库打开的监听
.setDbOpenListener(new DbManager.DbOpenListener() { @Override
public void onDbOpened(DbManager db) {
//开启数据库支持多线程操作,提升性能
db.getDatabase().enableWriteAheadLogging();
}
});
DbManager db = x.getDb(daoConfig);
然后创建数据库表ChildInfo实体类:
/**
* onCreated = "sql":当第一次创建表需要插入数据时候在此写sql语句
*/@Table(name = "child_info",onCreated = "")public class ChildInfo { /**
* name = "id":数据库表中的一个字段
* isId = true:是否是主键
* autoGen = true:是否自动增长
* property = "NOT NULL":添加约束
*/
@Column(name = "id",isId = true,autoGen = true,property = "NOT NULL") private int id; @Column(name = "c_name") private String cName;
public ChildInfo(String cName) { this.cName = cName;
} //默认的构造方法必须写出,如果没有,这张表是创建不成功的
public ChildInfo() {
} public int getId() { return id;
} public void setId(int id) { this.id = id;
} public String getcName() { return cName;
} public void setcName(String cName) { this.cName = cName;
} @Override
public String toString() { return "ChildInfo{"+"id="+id+",cName='"+cName+'\''+'}';
}
}
再然后创建和删除数据库的操作都可以进行了
//创建数据库@Event(R.id.create_db)private void createDB(View v) throws DbException { //用集合向child_info表中插入多条数据
ArrayList childInfos = new ArrayList<>();
childInfos.add(new ChildInfo("zhangsan"));
childInfos.add(new ChildInfo("lisi"));
childInfos.add(new ChildInfo("wangwu"));
childInfos.add(new ChildInfo("zhaoliu"));
childInfos.add(new ChildInfo("qianqi"));
childInfos.add(new ChildInfo("sunba")); //db.save()方法不仅可以插入单个对象,还能插入集合
db.save(childInfos);
}
//删除数据库@Event(R.id.del_db)private void delDB(View v) throws DbException {
db.dropDb();
}
2.删除表
//删除表@Event(R.id.del_table)private void delTable(View v) throws DbException {
db.dropTable(ChildInfo.class);
}
3.查询表中的数据
//查询表中的数据@Event(R.id.select_table)private void selelctDB(View v) throws DbException { //查询数据库表中第一条数据
ChildInfo first = db.findFirst(ChildInfo.class);
Log.i("JAVA",first.toString()); //添加查询条件进行查询
//第一种写法:
WhereBuilder b = WhereBuilder.b();
b.and("id",">",2); //构造修改的条件
b.and("id","<",4); List all = db.selector(ChildInfo.class).where(b).findAll();//findAll():查询所有结果
for(ChildInfo childInfo :all){
Log.i("JAVA",childInfo.toString());
} //第二种写法:
List all = db.selector(ChildInfo.class).where("id",">",2).and("id","<",4).findAll(); for(ChildInfo childInfo :all){
Log.i("JAVA",childInfo.toString());
}
}
4.修改表中的数据
//修改表中的一条数据@Event(R.id.update_table)private void updateTable(View v) throws DbException { //第一种写法:
ChildInfo first = db.findFirst(ChildInfo.class);
first.setcName("zhansan2");
db.update(first,"c_name"); //c_name:表中的字段名
//第二种写法:
WhereBuilder b = WhereBuilder.b();
b.and("id","=",first.getId()); //构造修改的条件
KeyValue name = new KeyValue("c_name","zhansan3");
db.update(ChildInfo.class,b,name); //第三种写法:
first.setcName("zhansan4");
db.saveOrUpdate(first);
}
5.删除表中的数据
@Event(R.id.del_table_data)private void delTableData(View v) throws DbException { //第一种写法:
db.delete(ChildInfo.class); //child_info表中数据将被全部删除
//第二种写法,添加删除条件:
WhereBuilder b = WhereBuilder.b();
b.and("id",">",2); //构造修改的条件
b.and("id","<",4);
db.delete(ChildInfo.class, b);
}
原文链接:http://www.apkbus.com/blog-815579-62069.html