An_Retrofit+Rxjava(checkbox)

首先我们要做的是添加各种依赖:
先看我的build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    defaultConfig {
        applicationId "com.example.mvprecyclerviewretrofitrxjavademo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.facebook.fresco:fresco:0.11.0'
}

再然后我用的是MVP模式写的Recyclerview实现
Recyclerview在MainActivity中显示

我们运用Retrofit和Rxjava 要添加一个包:retrofit
retrofit里面有一个接口:RetroAPI

package com.example.mvprecyclerviewretrofitrxjavademo.retrofit;

import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import rx.Observable;

/**
 * 作者:author
 * 说明:
 */

public interface RetroAPI {
    @GET("v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0")
    Observable getRetro();
    OkHttpClient CLIENT=new OkHttpClient.Builder()
            .addInterceptor(new LoggingInterceptor())
            .build();
    Retrofit RETROFIT=new Retrofit.Builder()
            .baseUrl("http://tingapi.ting.baidu.com/")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(CLIENT)
            .build();
    RetroAPI RETRO_API=RETROFIT.create(RetroAPI.class);
}

可以看出我们在API里面创建了Retrofit,以及ok的拦截器
那么我们给出的拦截器(网络拦截器)实例是:LoggingInterceptor
这个实例是不需要我们写的,但是没有加网络拦截器的话,就会请求不到地址(其他的接口可能没有此拦截器)

package com.example.mvprecyclerviewretrofitrxjavademo.retrofit;

import android.os.Build;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络拦截器
 */

public class LoggingInterceptor implements Interceptor {
    private static final String UA = "User-Agent";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader(UA, makeUA())
                .build();
        return chain.proceed(request);
    }

    private String makeUA() {
        String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
        return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;
    }

}

MyApp: 初始化fresco 别忘了在清单文件里加入name
以及在清单文件里加入网络权限*******

package com.example.testzhoukaotablayoutretrofit;

import android.app.Application;

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

/**
 * 作者:author
 * 时间 :
 * 说明:
 */

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}

Model:
IshowModel

package com.example.mvprecyclerviewretrofitrxjavademo.model;

import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;

import java.util.List;

/**
 * 作者:author
 * 说明:
 */

public interface IshowModel {
    public void showData(Callback callback);
    interface Callback{
        void complate(List listb);
    }
}

ShowModel:

package com.example.mvprecyclerviewretrofitrxjavademo.model;

import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;
import com.example.mvprecyclerviewretrofitrxjavademo.retrofit.RetroAPI;

import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者:author
 * 时间 :
 * 说明:
 */

public class showModel implements IshowModel {
    @Override
    public void showData(final Callback callback) {
        RetroAPI.RETRO_API.getRetro()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RetroBean retroBean) {
                        List list=retroBean.getSong_list();
                        callback.complate(list);
                    }
                });
    }
}

view:

package com.example.mvprecyclerviewretrofitrxjavademo.view;

import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;

import java.util.List;

/**
 * 作者:author
 * 说明:
 */

public interface IshowView {
    public void getData(List listb);
}

presenter:
Ipresenter接口:

package com.example.testzhoukaotablayoutretrofit.presenter;

/**
 * 作者:author
 * 时间 :
 * 说明:
 */

public interface Ipresenter {
    void attach(T view);
    void detach();
}

Presenter类

package com.example.mvprecyclerviewretrofitrxjavademo.presenter;

import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;
import com.example.mvprecyclerviewretrofitrxjavademo.model.IshowModel;
import com.example.mvprecyclerviewretrofitrxjavademo.model.showModel;
import com.example.mvprecyclerviewretrofitrxjavademo.view.IshowView;

import java.lang.ref.SoftReference;
import java.util.List;

/**
 * 作者:author
 * 说明:
 */

public class ShowPresenter implements Ipresenter {
    IshowModel model;
    IshowView view;
    SoftReference srf;
    public ShowPresenter( IshowView view){
        this.view=view;
        model=new showModel();
        attach(view);
    }
    public void showData(){
        model.showData(new IshowModel.Callback() {
            @Override
            public void complate(List listb) {
                srf.get().getData(listb);
            }
        });
    }
    @Override
    public void attach(IshowView view) {
        srf=new SoftReference(view);
    }

    @Override
    public void detach() {
        srf.clear();
    }
}

Adapter:

package com.example.mvprecyclerviewretrofitrxjavademo.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.mvprecyclerviewretrofitrxjavademo.R;
import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.HashMap;
import java.util.List;

/**
 * 作者:author
 * 说明:
 */

public class MyAdapter extends RecyclerView.Adapter {
    Context context;
    List listb;
    private boolean isShow = false;
    private boolean isSelect = false;
    private static HashMap isSelected;
    public MyAdapter(Context context, List listb,boolean isShow,boolean isSelect) {
        this.context = context;
        this.listb = listb;
        isSelected = new HashMap();
        this.isShow=isShow;
        this.isSelect=isSelect;
    }

    @Override
    public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view=View.inflate(context,R.layout.items,null);
        myViewHolder myViewHolder = new myViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final myViewHolder holder, int position) {
        holder.tvs.setText(listb.get(position).getTitle());
        DraweeController controller= Fresco.newDraweeControllerBuilder()
                .setUri(listb.get(position).getPic_small())
                .setAutoPlayAnimations(true)
                .build();
        holder.sdv.setController(controller);

        if(isShow){
            holder.checkboxnum.setVisibility(View.VISIBLE);
            holder.checkboxnum.setChecked(isSelect);

        }else{
            holder.checkboxnum.setVisibility(View.GONE);
        }
    }
    @Override
    public int getItemCount() {
        return listb==null?0:listb.size();
    }

    class myViewHolder extends RecyclerView.ViewHolder{
        TextView tvs;
        CheckBox checkboxnum;
        SimpleDraweeView sdv;
        public myViewHolder(View itemView) {
            super(itemView);
            tvs=itemView.findViewById(R.id.tvs);
            checkboxnum=itemView.findViewById(R.id.checkboxnum);
            sdv=itemView.findViewById(R.id.sdv);
        }
    }

}

MainActivity:

package com.example.mvprecyclerviewretrofitrxjavademo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.mvprecyclerviewretrofitrxjavademo.adapter.MyAdapter;
import com.example.mvprecyclerviewretrofitrxjavademo.bean.RetroBean;
import com.example.mvprecyclerviewretrofitrxjavademo.presenter.ShowPresenter;
import com.example.mvprecyclerviewretrofitrxjavademo.view.IshowView;

import java.util.List;

public class MainActivity extends BaseActivity implements IshowView, View.OnClickListener {

    private RecyclerView mRv;
    ShowPresenter presenter;
    MyAdapter myAdapter;
    List lists;
    List list;
    boolean isshow = true;
    CheckBox checkboxall;
    private Button mBtback;
    private TextView mBianji;
    private RelativeLayout mLlhead;
    private LinearLayout mLl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        presenter.showData();
        initView();

    }

    @Override
    protected void createpresenter() {
        presenter = new ShowPresenter(this);
    }

    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        mRv.setLayoutManager(llm);
        checkboxall = (CheckBox) findViewById(R.id.checkboxall);
        mBtback = (Button) findViewById(R.id.btback);
        mBtback.setOnClickListener(this);
        mBianji = (TextView) findViewById(R.id.bianji);
        mLlhead = (RelativeLayout) findViewById(R.id.llhead);
        mLl = (LinearLayout) findViewById(R.id.ll);
        checkboxall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean b) {
                if(b){
                    mRv.setAdapter(new MyAdapter(MainActivity.this,lists,true,true));
                }else{
                    mRv.setAdapter(new MyAdapter(MainActivity.this,lists,true,false));
                }
            }
        });
        mBianji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isshow){
                    mBianji.setText("完成");
                    mLl.setVisibility(View.VISIBLE);
                    mRv.setAdapter(new MyAdapter( MainActivity.this,lists, isshow,false));
                    isshow = false;
                }else{
                    mBianji.setText("编辑");
                    mLl.setVisibility(View.GONE);
                    mRv.setAdapter(new MyAdapter( MainActivity.this,lists, isshow,false));
                    isshow = true;
                }
            }
        });
    }

    @Override
    public void getData(final List listb) {
        lists = listb;
        myAdapter = new MyAdapter(MainActivity.this, lists, false, false);
        mRv.setAdapter(myAdapter);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btback:
                if(isshow){
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setMessage("是否要退出");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    });
                    builder.setNegativeButton("否", null);
                    builder.create().show();
                }else{
                    mBianji.setText("编辑");
                    mLl.setVisibility(View.GONE);
                    mRv.setAdapter(new MyAdapter(MainActivity.this,lists,isshow,checkboxall.isChecked()));
                    isshow = true;
                }
                break;
            default:
                break;
        }
    }
}

Mvp解绑需要一个Base类来实现:
BaseActivity:

package com.example.mvprecyclerviewretrofitrxjavademo;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.mvprecyclerviewretrofitrxjavademo.presenter.Ipresenter;

/**
 * 作者:author
 * 说明:
 */

public abstract class BaseActivity extends Activity{
    T presenter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createpresenter();
    }

    protected abstract void createpresenter();

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

最后把布局show一下:
MainActivity的layout:



    
        

items条目的布局:




    

        
        
        
    


你可能感兴趣的:(An_Retrofit+Rxjava(checkbox))