Fresco+RecyclerView+OkHttp+ButterKnife传值+条目点击跳转

首先我们要导入依赖

compile 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
compile 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
compile 'com.squareup.okhttp3:okhttp:3.3.0'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.google.code.gson:gson:2.4'
compile 'com.facebook.fresco:fresco:0.11.0'
compile 'com.facebook.fresco:animated-gif:0.12.0'
compile 'com.facebook.fresco:animated-webp:0.12.0'
compile 'com.facebook.fresco:webpsupport:0.12.0'

首页的视图

MyActivity的代码

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.View;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public static final String path ="http://api.tianapi.com/meinv/?  key=7c8edc74ba11ce2b011efd8a81f34dfa&num=40";
    private RecyclerView recyclrview;
    private News bean;
    private MyAdapter myAdapter;
    @BindView(R.id.rc)
    RecyclerView rc;
    LinearLayoutManager mLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mLayoutManager= new LinearLayoutManager(this);
        rc.setLayoutManager(mLayoutManager);
        rc.setHasFixedSize(true);
        setOkHttp();
    }
    //RecyclerView+OkHttp+ButterKnife传值+条目点击跳转
    public void setOkHttp() {
        OkHttp.getAsync(path, new OkHttp.DataCallBack() {
            @Override
            public void requestFailure(Request request, IOException e) {

            }

            @Override
            public void requestSuccess(String result) throws Exception {
                Gson gson = new Gson();
                bean = gson.fromJson(result, News.class);
                setRecyclerView();
            }
        });
    }

        public void setRecyclerView() {
            rc.setLayoutManager(mLayoutManager);
            myAdapter = new MyAdapter(MainActivity.this, bean);
            myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent =new Intent(MainActivity.this,TwoActivity.class);
                    //传递网址到第二个页面
                    List<News.NewslistBean> newslist = bean.getNewslist();
                    String title = newslist.get(position).getPicUrl();

                    EventBus.getDefault().postSticky(new MyEventBus(title));
                    startActivity(intent);

                }
            });

            rc.setAdapter(myAdapter);

        }
}

MyApplation绑定Fresco

    public class MyApplation extends Application {

        @Override
        public void onCreate() {
            super.onCreate();
            Fresco.initialize(this);


        }
    }

MyAdapterRecyView的适配器

    import android.content.Context;
    import android.net.Uri;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import com.facebook.drawee.generic.RoundingParams;
    import com.facebook.drawee.view.SimpleDraweeView;

    import java.net.URL;

        public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

        private Context context;
        private News news;
        //条目点击事件
        private OnItemClickListener onItemClickListener;

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        public interface OnItemClickListener{
            void onItemClick(View view, int position);
        }



        public MyAdapter(Context context, News news) {
            this.context = context;
            this.news = news;
        }

        //创建新View,被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            ViewHolder holder = new ViewHolder(LayoutInflater.from(context)
                    .inflate(R.layout.item, viewGroup, false));

            return holder;
        }
        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
            viewHolder.title.setText(news.getNewslist().get(position).getTitle());
            viewHolder.time.setText(news.getNewslist().get(position).getCtime());
            Uri uri = Uri.parse(news.getNewslist().get(position).getPicUrl());
            viewHolder.img.setImageURI(uri);
            //点击跳转到第二个页面
            if(onItemClickListener!=null){
                ((ViewHolder) viewHolder).ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onItemClickListener.onItemClick(viewHolder.itemView,position);
                    }
                });
            }

        }
        //获取数据的数量
        @Override
        public int getItemCount() {
            return news.getNewslist().size();
        }
        //自定义的ViewHolder,持有每个Item的的所有界面元素
        public static class ViewHolder extends RecyclerView.ViewHolder {
            public TextView title;
            public TextView time;
            public SimpleDraweeView img;
            private final LinearLayout ll;

            public ViewHolder(View view){
                super(view);
                ll = view.findViewById(R.id.ll);
                img   =(SimpleDraweeView) view.findViewById(R.id.img);
                title = (TextView) view.findViewById(R.id.title);
                time = (TextView) view.findViewById(R.id.time);

                RoundingParams roundingParams = RoundingParams.fromCornersRadius(5f);
                roundingParams.setBorder(R.color.red, 1);
                roundingParams.setRoundAsCircle(true);
                img.getHierarchy().setRoundingParams(roundingParams);
            }
        }
    }

MyEventBus传递值用的类

    public class MyEventBus {

        String s ;


        public MyEventBus(String s) {
            this.s = s;
        }


        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }
    }

OkHttp网络请求的类直接粘贴就行

import android.os.Handler;
import android.os.Looper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp {
/**
* 静态实例
*/
private static OkHttp sOkHttpManager;

/**
 * okhttpclient实例
 */
private OkHttpClient mClient;

/**
 * 因为我们请求数据一般都是子线程中请求,在这里我们使用了handler
 */
private Handler mHandler;

/**
 * 构造方法
 */
private OkHttp() {

    mClient = new OkHttpClient();

    /**
     * 在这里直接设置连接超时.读取超时,写入超时
     */
    mClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
    mClient.newBuilder().readTimeout(10, TimeUnit.SECONDS);
    mClient.newBuilder().writeTimeout(10, TimeUnit.SECONDS);

    /**
     * 如果是用的3.0之前的版本  使用以下直接设置连接超时.读取超时,写入超时
     */

    //client.setConnectTimeout(10, TimeUnit.SECONDS);
    //client.setWriteTimeout(10, TimeUnit.SECONDS);
    //client.setReadTimeout(30, TimeUnit.SECONDS);


    /**
     * 初始化handler
     */
    mHandler = new Handler(Looper.getMainLooper());
}


/**
 * 单例模式  获取OkHttp实例
 *
 * @return
 */
public static OkHttp getInstance() {

    if (sOkHttpManager == null) {
        sOkHttpManager = new OkHttp();
    }
    return sOkHttpManager;
}

//-------------------------同步的方式请求数据--------------------------

/**
 * 对外提供的get方法,同步的方式
 *
 * @param url 传入的地址
 * @return
 */
public static Response getSync(String url) {

    //通过获取到的实例来调用内部方法
    return sOkHttpManager.inner_getSync(url);
}

/**
 * GET方式请求的内部逻辑处理方式,同步的方式
 *
 * @param url
 * @return
 */
private Response inner_getSync(String url) {
    Request request = new Request.Builder().url(url).build();
    Response response = null;
    try {
        //同步请求返回的是response对象
        response = mClient.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

/**
 * 对外提供的同步获取String的方法
 *
 * @param url
 * @return
 */
public static String getSyncString(String url) {
    return sOkHttpManager.inner_getSyncString(url);
}


/**
 * 同步方法
 */
private String inner_getSyncString(String url) {
    String result = null;
    try {
        /**
         * 把取得到的结果转为字符串,这里最好用string()
         */
        result = inner_getSync(url).body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

//-------------------------异步的方式请求数据--------------------------
public static void getAsync(String url, DataCallBack callBack) {
    getInstance().inner_getAsync(url, callBack);
}

/**
 * 内部逻辑请求的方法
 *
 * @param url
 * @param callBack
 * @return
 */
private void inner_getAsync(String url, final DataCallBack callBack) {
    final Request request = new Request.Builder().url(url).build();

    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            deliverDataFailure(request, e, callBack);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = null;
            try {
                result = response.body().string();
            } catch (IOException e) {
                deliverDataFailure(request, e, callBack);
            }
            deliverDataSuccess(result, callBack);
        }
    });
}


/**
 * 分发失败的时候调用
 *
 * @param request
 * @param e
 * @param callBack
 */
private void deliverDataFailure(final Request request, final IOException e, final DataCallBack callBack) {
    /**
     * 在这里使用异步处理
     */
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack != null) {
                callBack.requestFailure(request, e);
            }
        }
    });
}

/**
 * 分发成功的时候调用
 *
 * @param result
 * @param callBack
 */
private void deliverDataSuccess(final String result, final DataCallBack callBack) {
    /**
     * 在这里使用异步线程处理
     */
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack != null) {
                try {
                    callBack.requestSuccess(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

/**
 * 数据回调接口
 */
public interface DataCallBack {
    void requestFailure(Request request, IOException e);

    void requestSuccess(String result) throws Exception;
}

//-------------------------提交表单--------------------------

public static void postAsync(String url, Map<String, String> params, DataCallBack callBack) {
    getInstance().inner_postAsync(url, params, callBack);
}

private void inner_postAsync(String url, Map<String, String> params, final DataCallBack callBack) {

    RequestBody requestBody = null;
    if (params == null) {
        params = new HashMap<>();
    }

    /**
     * 如果是3.0之前版本的,构建表单数据是下面的一句
     */
    //FormEncodingBuilder builder = new FormEncodingBuilder();

    /**
     * 3.0之后版本
     */
    FormBody.Builder builder = new FormBody.Builder();

    /**
     * 在这对添加的参数进行遍历,map遍历有四种方式,如果想要了解的可以网上查找
     */
    for (Map.Entry<String, String> map : params.entrySet()) {
        String key = map.getKey().toString();
        String value = null;
        /**
         * 判断值是否是空的
         */
        if (map.getValue() == null) {
            value = "";
        } else {
            value = map.getValue();
        }
        /**
         * 把key和value添加到formbody中
         */
        builder.add(key, value);
    }
    requestBody = builder.build();
    //结果返回
    // 请求对象
    final Request request = new Request.Builder().url(url).post(requestBody).build();
    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            deliverDataFailure(request, e, callBack);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = response.body().string();
            deliverDataSuccess(result, callBack);
        }


    });
}


//-------------------------文件下载--------------------------
public static void downloadAsync(String url, String desDir, DataCallBack callBack) {
    getInstance().inner_downloadAsync(url, desDir, callBack);
}

/**
 * 下载文件的内部逻辑处理类
 *
 * @param url      下载地址
 * @param desDir   目标地址
 * @param callBack
 */
private void inner_downloadAsync(final String url, final String desDir, final DataCallBack callBack) {
    final Request request = new Request.Builder().url(url).build();
    mClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            deliverDataFailure(request, e, callBack);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            /**
             * 在这里进行文件的下载处理
             */
            InputStream inputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                //文件名和目标地址
                File file = new File(desDir, getFileName(url));
                //把请求回来的response对象装换为字节流
                inputStream = response.body().byteStream();
                fileOutputStream = new FileOutputStream(file);
                int len = 0;
                byte[] bytes = new byte[2048];
                //循环读取数据
                while ((len = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, len);
                }
                //关闭文件输出流
                fileOutputStream.flush();
                //调用分发数据成功的方法
                deliverDataSuccess(file.getAbsolutePath(), callBack);
            } catch (IOException e) {
                //如果失败,调用此方法
                deliverDataFailure(request, e, callBack);
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }

            }
        }

    });
}

/**
 * 根据文件url获取文件的路径名字
 *
 * @param url
 * @return
 */
private String getFileName(String url) {
    int separatorIndex = url.lastIndexOf("/");
    String path = (separatorIndex < 0) ? url : url.substring(separatorIndex + 1, url.length());
    return path;
}

}

第二个页面TwoActivity

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TwoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        //注册eventbus
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);

    }


    @Subscribe(sticky = true)
    public void  jie(MyEventBus myEventBus){
        String s = myEventBus.getS();
       // Toast.makeText(TwoActivity.this, s, Toast.LENGTH_SHORT).show();
       // Log.d("===",s);
        aa(s);
    }

public void aa(String s){
    Uri uri = Uri.parse(s);
    SimpleDraweeView sd= findViewById(R.id.sd);
    sd.setImageURI(uri);

}

protected void onDestroy() {
    //解除注册
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}

}

第二个页面的视图

item的视图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值