涉及到RecycleView的使用okHttp的使用 以及对get和post的简单封装
compile 'com.android.support:recyclerview-v7:24.+'
compile 'com.android.support:cardview-v7:24.+'
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.github.d-max:spots-dialog:0.4@aar'
一.RecycleView的使用
http://blog.csdn.net/lmj623565791/article/details/45059587
1.初始化recycleView
/**
* 设置recycleView
*/
private void initRecycleView() {
datas = new ArrayList<HomeCategory>();
HomeCategory category = new HomeCategory("热门活动", R.drawable.img_big_1, R.drawable.img_1_small1, R.drawable.img_1_small2);
datas.add(category);
category = new HomeCategory("有利可图", R.drawable.img_big_4, R.drawable.img_4_small1, R.drawable.img_4_small2);
datas.add(category);
category = new HomeCategory("品牌街", R.drawable.img_big_2, R.drawable.img_2_small1, R.drawable.img_2_small2);
datas.add(category);
category = new HomeCategory("金融街 包赚翻", R.drawable.img_big_1, R.drawable.img_3_small1, R.drawable.imag_3_small2);
datas.add(category);
category = new HomeCategory("超值购", R.drawable.img_big_0, R.drawable.img_0_small1, R.drawable.img_0_small2);
datas.add(category);
recyclerView.setAdapter(new HomeCategoryAdapter(datas));
recyclerView.addItemDecoration(new DividerItemDecortion());//设置分割线
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
}
2.设置recycleView的适配器
public class HomeCategoryAdapter extends RecyclerView.Adapter<HomeCategoryAdapter.ViewHolder> {
private LayoutInflater mInflater;
private static int VIEW_TYPE_L=0;
private static int VIEW_TYPE_R=1;
private List<HomeCategory> datas;
public HomeCategoryAdapter(List<HomeCategory> datas) {
this.datas = datas;
}
//返回holder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mInflater = LayoutInflater.from(parent.getContext());
if(viewType == VIEW_TYPE_R){
return new ViewHolder(mInflater.inflate(R.layout.template_home_cardview2,parent,false));
}
return new ViewHolder(mInflater.inflate(R.layout.template_home_cardview,parent,false));
}
//设置recycleView的数据
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
HomeCategory category = datas.get(position);
holder.textTitle.setText(category.getName());
holder.imageViewBig.setImageResource(category.getImgBig());
holder.imageViewSmallTop.setImageResource(category.getImgSmallTop());
holder.imageViewSmallBottom.setImageResource(category.getImgSmallBottom());
}
@Override
public int getItemCount() {
return datas.size();
}
//设置两种不同的holder的返回类型
@Override
public int getItemViewType(int position) {
if(position % 2==0){
return VIEW_TYPE_R;
}
else return VIEW_TYPE_L;
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView textTitle;
ImageView imageViewBig;
ImageView imageViewSmallTop;
ImageView imageViewSmallBottom;
public ViewHolder(View itemView) {
super(itemView);
textTitle = (TextView) itemView.findViewById(R.id.text_title);
imageViewBig = (ImageView) itemView.findViewById(R.id.imgview_big);
imageViewSmallTop = (ImageView) itemView.findViewById(R.id.imgview_small_top);
imageViewSmallBottom = (ImageView) itemView.findViewById(R.id.imgview_small_bottom);
}
}
}
3.关于设置分割线样式(网上有详细介绍)
/**
* Created by asus on 2016/10/22.
* 自定义分割线
*/
public class DividerItemDecortion extends RecyclerView.ItemDecoration {
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.top = 10;
outRect.left=5;
outRect.right=5;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
}
}
4.使用cardView(网上介绍)
二.Okhttp的使用
详细介绍见(转载分类)http://blog.csdn.net/lmj623565791/article/details/47911083
1.简单的get和提交post表单的使用
String url = "http://112.124.22.238:8081/course_api/banner/query";
// String url = "http://112.124.22.238:8081/course_api/banner/query?type=1";
OkHttpClient okHttpClient = new OkHttpClient();
//post表单到服务器
RequestBody body = new FormEncodingBuilder()
.add("type", "1")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)//通过post的表单数据获得json
.build();
// 异步请求数据
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String jsonData = response.body().string();
parseGson(jsonData);
}
}
});
2.解析json数据(通过gson)
public void parseGson(String jsonData) {
Gson gson = new Gson();
Type type = new TypeToken<List<Banner>>() {}.getType();
mbanner = gson.fromJson(jsonData, type);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
initSlider();//2.设置网络数据到轮播条 该操作需哟放到主线程中
}
});
}
3.设置数据到轮播条中(采用的AndroidImageSlide)
//设置轮播
if (mbanner != null) {
for (Banner banner : mbanner) {
TextSliderView textSliderView = new TextSliderView(getActivity());
textSliderView.image(banner.getImgUrl());
textSliderView.description(banner.getName());
textSliderView.setScaleType(BaseSliderView.ScaleType.Fit);
mSliderLayout.addSlider(textSliderView);
}
}
三.Okhttp的简单封装
1.封装类
**
* Created by asus on 2016/10/23.
* <p>
* 封装OkHttp
*/
public class OkHttpHelper {
private OkHttpClient mHttpClient;
private Gson gson;
private Handler handler;
//单例
private static OkHttpHelper okHttpHelper = new OkHttpHelper();
//初始化
private OkHttpHelper() {
mHttpClient = new OkHttpClient();
mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);
gson = new Gson();
handler = new Handler(Looper.getMainLooper());
}
public static OkHttpHelper getInstance() {
return okHttpHelper;
}
//get请求
public void get(String url, BaseCallback callback) {
Request request = buildRequest(url, null, HttpMethodType.GET);
doRequest(request, callback);
}
//post请求
public void post(String url, HashMap<String, String> params, BaseCallback callback) {
Request request = buildRequest(url, null, HttpMethodType.POST);
doRequest(request, callback);
}
//返回一个请求body
private RequestBody buildFromData(HashMap<String, String> params) {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
if(params!=null){
for(HashMap.Entry<String,String> map:params.entrySet()){
formEncodingBuilder.add(map.getKey(),map.getValue());
}
}
return formEncodingBuilder.build();
}
//1.创建一个request对象
public Request buildRequest(String url, HashMap<String, String> params, HttpMethodType methodType) {
Request.Builder builder = new Request.Builder();
builder.url(url);
if (methodType == HttpMethodType.GET) {//如果是get请求
builder.get();//创建获取方法
} else {
RequestBody body = buildFromData(params);//如果是post请求就进行表单的设置
builder.post(body);//创建post方法
}
return builder.build();
}
public enum HttpMethodType {
GET,
POST
}
//使用handler在主线程执行成功和错误的方法
public void callbackSuccess(final BaseCallback callback, final Response response, final Object obj){
handler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(response,obj);
}
});
}
private void callbackError(final BaseCallback callback , final Response response, final Exception e ){
handler.post(new Runnable() {
@Override
public void run() {
callback.onError(response,response.code(),e);
}
});
}
//2.开始请求
public void doRequest(Request request, final BaseCallback callback) {//自定义callback
callback.onBeforeRequest(request);//1.请求之前回调
mHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
SystemClock.sleep(1000);
callback.onResponse(response);
if(response.isSuccessful()){
String resultStr = response.body().string();
if(callback.mType==String.class){//如果类型是String,直接返回,不用解析
callback.onSuccess(response,resultStr);
}else{ //需要解析
try {
Object object = gson.fromJson(resultStr, callback.mType);
callbackSuccess(callback,response,object);
} catch (JsonParseException e) {//解析错误异常
e.printStackTrace();
}
}
}else{
callbackError(callback,response,null);
}
}
});
}
}
2.自定义的callback类
**
* Created by asus on 2016/10/23.
*/
public abstract class BaseCallback<T> {
//获取type类型
public Type mType;
static Type getSuperclassTypeParameter(Class<?> subclass)
{
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class)
{
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
public BaseCallback()
{
mType = getSuperclassTypeParameter(getClass());
}
//自定义方法在请求之前调用
public abstract void onBeforeRequest(Request request);
//失败调用(复写原OnFailure)
public abstract void onFailure(Request request, Exception e) ;
/**
*请求成功时调用此方法
* @param response
*/
public abstract void onResponse(Response response);
/**
*
* 状态码大于200,小于300 时调用此方法
* @param response
* @param t
* @throws IOException
*/
public abstract void onSuccess(Response response,T t) ;
/**
* 状态码400,404,403,500等时调用此方法
* @param response
* @param code
* @param e
*/
public abstract void onError(Response response, int code,Exception e) ;
}
3.定义Dialog的callback继承baseCallback
public abstract class SpotsCallBack<T> extends BaseCallback<T> {
private Context mContext;
private SpotsDialog mDialog;
public SpotsCallBack(Context context){
mContext = context;
initSpotsDialog();
}
private void initSpotsDialog(){
mDialog = new SpotsDialog(mContext,"拼命加载中...");
}
public void showDialog(){
mDialog.show();
}
public void dismissDialog(){
mDialog.dismiss();
}
public void setLoadMessage(int resId){
mDialog.setMessage(mContext.getString(resId));
}
@Override
public void onFailure(Request request, Exception e) {
dismissDialog();
}
@Override
public void onBeforeRequest(Request request) {
showDialog();
}
@Override
public void onResponse(Response response) {
dismissDialog();
}
}
4.使用封装的okHttp
httpHelper.get(url, new SpotsCallBack<List<Banner>>(getContext()){
@Override
public void onSuccess(Response response, List<Banner> banners) {
mBanner = banners;
initSlider();
}
@Override
public void onError(Response response, int code, Exception e) {
}
});