Retrofit、ButterKnife、Glide学习记录
来源:互联网 发布:车削编程讲解 编辑:程序博客网 时间:2024/06/15 22:35
今天是1024程序员节,发篇草稿箱里的博客庆祝下
- Retrofit初体验
- ButterKnife初体验
- 配置依赖
- 初步使用
- Data Binding
- Glide初体验
- 初步使用
- 其他配置
Retrofit初体验
这里我以请求手机号码归属地的接口为例:
http://api.k780.com:88/?app=phone.get&phone=15250881234&appkey=20584&sign=6e56a4fcbaad03fc91269c8527d2b39c&format=json
1,添加gradle依赖
compile 'com.squareup.retrofit2:retrofit:2.1.0'; compile 'com.squareup.retrofit2:converter-gson:2.1.0'; compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0';
如果代码里有其他jar包或者依赖已经集成过okhttp,那么就得改成如下方式了
compile('com.squareup.retrofit2:retrofit:2.1.0') { exclude group: 'com.squareup.okhttp3' } compile('com.squareup.retrofit2:converter-gson:2.1.0') { exclude group: 'com.google.code.gson' exclude group: 'com.squareup.okhttp3' } compile('com.squareup.retrofit2:adapter-rxjava:2.1.0') { exclude group: 'io.reactivex' exclude group: 'com.squareup.okhttp3' }
2,请求接口的定制
public interface RetrofitRequest { @GET("/") Call<MobileBean> getMobileArea(@QueryMap Map<String, String> params); // queryMap// 以下为非map参数// Call<MobileBean> getMobileArea(@Query("app") String app, @Query("phone") String phone,// @Query("appkey") String appkey, @Query("sign") String sign, @Query("format") String format); // query}
3,retrofit方法的封装
/** * url http://api.k780.com:88/?app=phone.get&phone=15250881234&appkey=20584&sign=6e56a4fcbaad03fc91269c8527d2b39c&format=json * @param phoneNum * @return */ public static String retrofitWithGet(String phoneNum){ String result; Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://api.k780.com:88") .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitRequest service = retrofit.create(RetrofitRequest.class); Map<String, String> params = new HashMap<String, String>(); params.put("app", "phone.get"); params.put("phone", phoneNum); params.put("appkey", "20584"); params.put("sign", "6e56a4fcbaad03fc91269c8527d2b39c"); params.put("format", "json"); Call<MobileBean> callback = service.getMobileArea(params);// Call<MobileBean> callback = service.getMobileArea("phone.get","15250881234","20584", "6e56a4fcbaad03fc91269c8527d2b39c", "json"); try { // 以下为同步方法 MobileBean mobileBean = callback.execute().body(); if(mobileBean.getSuccess().equals("1")) { result = mobileBean.getResult().getAtt().substring(3); }else{ LogUtil.i("retrofitWithGet","出现失败"); result = "江苏,淮安"; } } catch (IOException e) { e.printStackTrace(); LogUtil.i("retrofitWithGet","出现异常"); result = "江苏,淮安"; } return result; // 以下为异步方法// callback.enqueue(new Callback<MobileBean>() {// @Override// public void onResponse(Call<MobileBean> call, Response<MobileBean> response) {// MobileBean mobileBean = response.body();// String// LogUtil.i("NetwotkUtils","地址:"+ area);//// }//// @Override// public void onFailure(Call<MobileBean> call, Throwable t) {// LogUtil.i("NetwotkUtils","retrofit请求失败"+t.getMessage());// }// }); }
4,调用
retrofitWithGet("15250881234");
5,TransformException: java.util.zip.ZipException: duplicate entry: okhttp3/Address.class
此类问题的解决方法:compile Retrofit的配置加下exclude(如第一步的代码),把重复的okhttp除去。 可参考:http://www.th7.cn/Program/Android/201610/982828.shtml把重复的gson包去除
bmob官方解答:http://docs.bmob.cn/data/Android/h_2android_datahelps/doc/index.html#其它问题
和bmob使用的冲突:http://m.blog.csdn.net/article/details?id=52779722
ButterKnife初体验
配置依赖
根据Github上的介绍,在项目的build.gradle中添加classpath
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:2.2.0' // ButterKnife 需要添加此项 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' } }
以及在module的build.gradle中添加dependencies
apply plugin: 'android-apt'dependencies {compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0'}
这样初始化配置就算完成了,下面就可以正常使用注解框架了
初步使用
详细配置请参考官方Github
compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0'
1,普通的findViewById
@BindView(R.id.aboutus_version_tv) TextView versionTV;
在OnCreate中加一行代码,就可以直接使用了
ButterKnife.bind(this); versionTV.setText("1.0")
2,View的点击事件,方法名随意
@OnClick(R.id.aboutus_protocol_layout) public void OnProtocolClick(){ startActivity(new Intent(AboutActivity.this, RegisterProtocolActivity.class)); }
3,Dialog的绑定
TextView qqTV = ButterKnife.findById(view, R.id.setting_qq_text);
4,去掉如下这类提示
The method xxx is Never be used
在方法上press Alt+Enter ,然后选择Suppress for methods annotated by ‘butterknife.OnClick’
至于怎么撤销这种操作,可以通过编辑.idea/misc.xml文件
<item index="0" class="java.lang.String" itemvalue="butterknife.OnClick" />
itemvalue的值butterknife.OnClick 可以改成 butterknife.*.
5,dialog、popupwindow、pageradapter、mNavigationView的headView 如何使用BindView和OnClick注解
6,封装的RecyclerViewHolder的findViewById替换
7,控件的声明不能是private或者static的
8,普通adapter的绑定,可以通过ViewHolder的构造方法传递view参数
9,错误error如下:
Required view ‘common_title_txt’ with ID 2131624198 for field ‘mTitleTV’ was not found. If this view is optional add ‘@Nullable’ (fields) or ‘@Optional’ (methods) annotation.
首先保证butterknife.bind方法要在setContentView之后,然后在遇到有内部类的适配器时,要注意ViewHolder中的注解使用
public ViewHolder(View view) { ButterKnife.bind(this,view); }
像上面这样就可以了,不要跟我一样自作聪明的把这个this换成MainActivity.this这样。
10,ButterKnifeZelezny插件的使用
PS,混淆:
-keep class butterknife.** { *; }-dontwarn butterknife.internal.**-keep class **$$ViewBinder { *; }-keepclasseswithmembernames class * { @butterknife.* <fields>;}-keepclasseswithmembernames class * { @butterknife.* <methods>;}
Data Binding
讲完了butterknife,不得不提data binding,毕竟和下面的Glide一样属于谷歌Android团队官方出品,看它的配置就很简单,在android标签下加入如下代码
dataBinding { enabled true }
然后布局文件要按照既定的模板格式去写,详细使用方法我也没细看,可参考这里
与此类似的注解框架还有:
- Roboguice https://github.com/roboguice/roboguice
- Dagger https://github.com/square/dagger
Glide初体验
Github地址https://github.com/bumptech/glide
初步使用
使用起来也只要三步:
第一:添加依赖
compile 'com.github.bumptech.glide:glide:3.7.0'
第二:图片工具类方法
public class ImageUtils { public static void displayImage(Context context, String url, ImageView imageView) { Glide.with(context).load(url).into(imageView); }}
第三:在合适的调用即可
其他配置
1,使用加载中图片,静态图或者动态gif
.placeholder(R.drawable.common_image_loading)
以上这个方法并不能显示动态gif,看下面
Glide.with(context) .load(url) .thumbnail(Glide.with(context).load(R.drawable.image_loading)) .into(imageView);
2,当使用到圆角图片时的解决方法( 相关问题点这里–>https://github.com/bumptech/glide/issues/528)
- 不使用动画,鉴于Glide默认是使用动画的,如果不使用的会感觉不太好看,所以不太推荐这种做法,仅供参考
.dontAnimate()
- 使用transform接口处理图片为圆角,可以参考https://github.com/wasabeef/glide-transformations这个库
.bitmapTransform(new CropCircleTransformation(context))
3,下载图片
可以参考这篇博文,http://www.cnblogs.com/csonezp/p/5124270.html
4,加载本地图片,包括SD卡,资源目录下等
Glide.with(context) .load(resourceId) // R.drawable.ic_launcher //.load(file) // /mnt/sdcard/demo.jpg .asBitmap() .placeholder(R.drawable.common_image_loading) // 加载中图片 .transform(new CropCircleTransformation(context))//图片显示圆形 .into(imageView);
5,使用Glide加载图片变形:第一次加载变形,然后滑动列表再滑回来或者设置成centerCrop就不会变形了,出现这种问题的罪魁祸首就是placeholder,解决办法有两个:
- 不使用placeholder
- placeholder的图片大小设置成你最终显示图片的大小,比如说头像的话,正方形就可以了
6,图片加载失败显示的错误图
http://stackoverflow.com/questions/35539081/glide-how-to-get-the-error-bitmap/41555443?noredirect=1#comment70538329_41555443
Glide.with(context).load(uri).asBitmap().into(new SimpleTarget<Bitmap>(width, height) { @Override public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { // add image to the imageView here imageView.setImageBitmap(resource); } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { // you are given the error drawable super.onLoadFailed(e, errorDrawable); imageView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.image_error)); }});
这样做了以后的确会显示加载失败的图片,但无法显示正在加载中的gif动图了
- Retrofit、ButterKnife、Glide学习记录
- Android学习资源-retrofit,eventBus,butterknife,fragment
- Rxandroid+Retrofit学习记录
- MVP“美”图+新闻+天气预报+Material+Rx+Retrofit+Glide+leakcanary+butterknife
- MVP模式+dagger2+ Glide + Retrofit+OkHttp+GreenDao + RxJava + butterknife(新人练手项目)
- butterknife 黄油刀 学习记录
- Retrofit 学习记录(一)
- Retrofit和Glide
- 记录Glide
- Retrofit 2.0 + OkHttp 3.0学习记录
- retrofit+koliten+lambda+glide+recyclerview
- 天气预报项目学习总结(- ButterKnife - Retrofit 2.0(okhttp) - Rxjava - Jackson - Ormlite - Mosby简单使用总结)
- ButterKnife学习
- ButterKnife学习
- ButterKnife学习
- 重构(MVP+Retrofit+Okhttp+Gson+Butterknife)
- butterKnife + retrofit + RxJava封装之路
- GreenDao+ButterKnife+Retrofit+Fresco展示网络数据
- C++检测标点符号
- Connection reset原因分析和解决方案
- ExtJs情景优化
- java 试题
- IF语句的反汇编判断
- Retrofit、ButterKnife、Glide学习记录
- 最简单js代码实现select二级联动下拉菜单(测试通过)
- 隐藏元素的三种方法:
- Android中的进程与线程
- Linux黑窗口状态下如何备份日志并下载到本地
- fragment之间的跳转
- Android Studio自定义模板
- request.getParameter(“参数名”) 中文乱码解决方法
- python与C++混合编程