XRecyclerView上拉下拉获取网络数据

本博客代码内容使用了:Retrofit+Rxjava+XRecyclerview+Fresco+Butterknife


//依赖

compile 'io.reactivex:rxjava:1.3.4'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.facebook.fresco:fresco:0.12.0'//fresco
compile 'com.jcodecraeer:xrecyclerview:1.3.2'//xrecyclerview
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'


//权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

//代码
activity_main1
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.recyclerview0412.view.MainActivity">

    <com.jcodecraeer.xrecyclerview.XRecyclerView
        android:id="@+id/xrv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.jcodecraeer.xrecyclerview.XRecyclerView>

</LinearLayout>

activity_main2
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.recyclerview0412.view.Main2Activity">

    <com.facebook.drawee.view.SimpleDraweeView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center_horizontal"
        android:id="@+id/img" />

</LinearLayout>
 
Item
 
 
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    xmlns:fresco="http://schemas.android.com/apk/res-auto">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/item_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_vertical"
        fresco:actualImageScaleType="focusCrop"
        fresco:placeholderImageScaleType="fitCenter"
        fresco:progressBarImageScaleType="centerInside"
        fresco:progressBarAutoRotateInterval="5000"
        fresco:failureImageScaleType="centerInside"
        fresco:retryImageScaleType="centerCrop"
        fresco:fadeDuration="5000">
    </com.facebook.drawee.view.SimpleDraweeView>

    <TextView
        android:layout_below="@id/item_img"
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

</LinearLayout>

Utils
 
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;

/**
 * Created by ass on 2018/04/12.
 */

public interface LogService {
    //    http://api.tianapi.com/meinv/?key=2a0024d1f7f558e09936f697580f1643&num=2000
    @GET("meinv/")
    Observable<ShowBean> getUrl(@Query("key") String key, @Query("num") int num);

}

//初始化fresco
 
import android.app.Application;

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

/**
 * Created by ass on 2018/04/12.
 */

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化fresco
        Fresco.initialize(this);
    }
}
ShowBean类
http://api.tianapi.com/meinv/?key=2a0024d1f7f558e09936f697580f1643&num=2000
 
model层
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ass on 2018/04/12.
 */

public class RetrofitUtils {
    private static volatile RetrofitUtils instance;
    private Retrofit retrofit;

    private RetrofitUtils(){

    }
    private RetrofitUtils(String baseUrl){
        OkHttpClient client = new OkHttpClient();
        retrofit = new Retrofit.Builder()
                .client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }
    public static RetrofitUtils getInstance(String baseUrl){
        if (instance==null){
            synchronized (RetrofitUtils.class){
                if (null==instance){
                    instance = new RetrofitUtils(baseUrl);
                }
            }
        }
        return instance;

    }
    public static RetrofitUtils getInstance(){
        if (null == instance){
            return  getInstance("http://api.tianapi.com/");
        }
        return instance;
    }
    public Retrofit getRetrofit(){
        return retrofit;
    }
}
 
Presenter层
 
import com.example.recyclerview0412.model.RetrofitUtils;
import com.example.recyclerview0412.utils.LogService;
import com.example.recyclerview0412.utils.ShowBean;
import com.example.recyclerview0412.view.NewsView;

import java.util.List;

import retrofit2.Retrofit;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by ass on 2018/04/12.
 */

public class NewsPresenter {
    private NewsView newsView;
    private Subscription subscribe;

    public void attachView(NewsView newsView){
        this.newsView = newsView;
    }
    public void getNews(String key,int num){
        Retrofit retrofit = RetrofitUtils.getInstance().getRetrofit();
        LogService service = retrofit.create(LogService.class);
        subscribe = service.getUrl(key,num)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ShowBean>() {
                    @Override
                    public void call(ShowBean jsonBean) {
                        List<ShowBean.NewslistBean> list = jsonBean.getNewslist();
                        newsView.success(list);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        newsView.failed(throwable.getMessage());
                    }
                });

    }
    public void detachView(){
        // 当Activity销毁的时候取消订阅时间,防止内存泄漏
        if (subscribe != null) {
            if (subscribe.isUnsubscribed()) {
                subscribe.unsubscribe();
            }
        }
        if (newsView!=null){
            newsView = null;
        }
    }
}

View层
NewsView 
 
import com.example.recyclerview0412.utils.ShowBean;

import java.util.List;

/**
 * Created by ass on 2018/04/12.
 */

public interface NewsView {
    void success(List<ShowBean.NewslistBean> data);
    void failed(String e);
}

适配器
 
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.recyclerview0412.R;
import com.example.recyclerview0412.utils.ShowBean;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

/**
 * Created by ass on 2018/04/12.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<ShowBean.NewslistBean> datas;
    private Context context;


    public MyAdapter(List<ShowBean.NewslistBean> datas, Context context) {
        this.datas = datas;
        this.context = context;
    }

    //创建新View,被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        //字条目布局
        View view = View.inflate(context, R.layout.item, null);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    //绑定ViewHolder,将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        viewHolder.item_img.setImageURI(datas.get(position).getPicUrl());
        viewHolder.mTextView.setText(datas.get(position).getTitle());
        viewHolder.item_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, Main2Activity.class);
                intent.putExtra("key", datas.get(position).getPicUrl());
                context.startActivity(intent);
            }
        });
    }

    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }

    //自定义的ViewHolder,持有每个Item的的所有界面元素
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;
        private SimpleDraweeView item_img;

        public ViewHolder(View view) {
            super(view);
            mTextView = (TextView) view.findViewById(R.id.text);
            item_img = view.findViewById(R.id.item_img);
        }
    }
}

 
MainActity
 
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;

import com.example.recyclerview0412.R;
import com.example.recyclerview0412.presenter.NewsPresenter;
import com.example.recyclerview0412.utils.ShowBean;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.xrv)
    XRecyclerView xrecycler;
    private NewsPresenter presenter;
    private List<ShowBean.NewslistBean> list = new ArrayList<>();
    private MyAdapter adapter;
    private int num=10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化fresco
        Fresco.initialize(this);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
        //将recyclerview设置成listview的布局样式
        LinearLayoutManager linLayoutManager = new LinearLayoutManager(this);
        linLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xrecycler.setLayoutManager(linLayoutManager);
        getData(num);
        //设置可上拉
        xrecycler.setPullRefreshEnabled(true);
        xrecycler.setLoadingMoreEnabled(true);
        //设置上拉下拉样式
        xrecycler.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrecycler.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
        //设置监听
        xrecycler.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        num=10;
                        getData(num);
                        xrecycler.refreshComplete();
                    }

                }, 2000);
            }

            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        num+=10;
                        getData(num);
                        xrecycler.refreshComplete();
                    }
                }, 2000);
            }
        });

    }
    public void getData(int count){
        presenter = new NewsPresenter();
        presenter.getNews("2a0024d1f7f558e09936f697580f1643", num);
        presenter.attachView(new NewsView() {
            @Override
            public void success(List<ShowBean.NewslistBean> data) {
                list.addAll(data);
                if (adapter==null){
                    adapter = new MyAdapter(list, MainActivity.this);
                    xrecycler.setAdapter(adapter);
                }else {
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void failed(String e) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter !=null){
            presenter.detachView();
        }
    }
}

 
Main2Activity 
 
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.example.recyclerview0412.R;
import com.facebook.drawee.view.SimpleDraweeView;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //获取控件
        SimpleDraweeView img = findViewById(R.id.img);

        Intent intent = getIntent();
        String key = intent.getStringExtra("key");
        img.setImageURI(Uri.parse(key));
    }
}
 
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值