1. 程式人生 > >RecyclerView和OKhttp

RecyclerView和OKhttp

RecyclerView 刪除條目 新增 更新 多條目的使用

首先匯入依賴
加許可權

<uses-permission android:name="android.permission.INTERNET"/>
  implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.google.code.gson:gson:2.2.4'
    implementation 'com.squareup.picasso:picasso:2.3.2'
    implementation 'com.google.guava:guava:16.0.1'

然後寫佈局 layout_main

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

OKhttp工具類

public class Tools {
    public Tools() {
    }
    public Tools get(String path){
        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.writeTimeout(3000, TimeUnit.MILLISECONDS);
        builder.readTimeout(3000,TimeUnit.MILLISECONDS);
        StringBuffer buffer = new StringBuffer();
        String s = buffer.toString();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json charset=utf-8"), s);
         Request request = new Request.Builder()
                .post(requestBody)
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                if (code==200){
                    ResponseBody body = response.body();
                    String string = body.string();
                        data.getDate(string);
                }
            }
        });
        return this;
    }
    private HttpDate data;
    public void setData(HttpDate data){
        this.data=data;
    }
    public interface HttpDate{
        void getDate(String s);
    }
}

Bean類

public class User {
    private String msg;
    private int code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * uniquekey : 1326bf3c4505783d4a964f81b6220e9d
         * title : 美國被特朗普坑慘了!又有3個鐵桿盟友公開唱對臺戲!
         * date : 2018-05-12 07:25
         * category : 頭條
         * author_name : 大國軍情
         * url : http://mini.eastday.com/mobile/180512072544020.html
         * thumbnail_pic_s : http://04.imgmini.eastday.com/mobile/20180512/20180512_fe1bf1b6ec00098f9455c84dc81e6763_cover_mwpm_03200403.jpg
         * thumbnail_pic_s02 : http://04.imgmini.eastday.com/mobile/20180512/20180512_3f636fca330f2311583896aed3185196_cover_mwpm_03200403.jpg
         * thumbnail_pic_s03 : http://04.imgmini.eastday.com/mobile/20180512/20180512_793fab03dadcd417bf2d8e5e1e48a0f5_cover_mwpm_03200403.jpg
         */

        private String uniquekey;
        private String title;
        private String date;
        private String category;
        private String author_name;
        private String url;
        private String thumbnail_pic_s;
        private String thumbnail_pic_s02;
        private String thumbnail_pic_s03;

        public String getUniquekey() {
            return uniquekey;
        }

        public void setUniquekey(String uniquekey) {
            this.uniquekey = uniquekey;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getAuthor_name() {
            return author_name;
        }

        public void setAuthor_name(String author_name) {
            this.author_name = author_name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getThumbnail_pic_s() {
            return thumbnail_pic_s;
        }

        public void setThumbnail_pic_s(String thumbnail_pic_s) {
            this.thumbnail_pic_s = thumbnail_pic_s;
        }

        public String getThumbnail_pic_s02() {
            return thumbnail_pic_s02;
        }

        public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
            this.thumbnail_pic_s02 = thumbnail_pic_s02;
        }

        public String getThumbnail_pic_s03() {
            return thumbnail_pic_s03;
        }

        public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
            this.thumbnail_pic_s03 = thumbnail_pic_s03;
        }
    }
}

RecyclerViewAdapter類

public class RecyclerViewAdapter extends Adapter {
    private List<User.DataBean> list;
    private Context mcontext;

    //3.全域性變數
    private RecycleitemClick click;

    public RecyclerViewAdapter(Context context, List<User.DataBean> list) {
        this.mcontext=context;
        this.list=list;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {

        View view;
        RecyclerView.ViewHolder holder = null;

        switch (position) {
            case 1:
                view = LayoutInflater.from(mcontext).inflate(R.layout.item, viewGroup, false);
                //傳入點選事件
                holder = new MyViewHolder(view, click);
                break;
            case 2:
                view = LayoutInflater.from(mcontext).inflate(R.layout.item1, viewGroup, false);
                holder = new MyViewHolder2(view, click);
                break;
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {

        User.DataBean bean = list.get(position);
        switch (getItemViewType(position)) {
            case 1:
                Picasso.with(mcontext).load(bean.getThumbnail_pic_s()).into(((MyViewHolder) viewHolder).image1);
                ((MyViewHolder) viewHolder).text1.setText(bean.getAuthor_name());
                break;
            case 2:
                Picasso.with(mcontext).load(bean.getThumbnail_pic_s()).into(((MyViewHolder2) viewHolder).image2);
                Picasso.with(mcontext).load(bean.getThumbnail_pic_s02()).into(((MyViewHolder2) viewHolder).image3);
                ((MyViewHolder2) viewHolder).text2.setText(bean.getAuthor_name());
                break;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position % 2 != 0) {
            return 1;
        } else {
            return 2;
        }
    }

    //刪除
    public void removeDate(int position) {
        list.remove(position);
        notifyItemRemoved(position);
        notifyDataSetChanged();
    }

    //新增
    public void addDate(int position) {
        list.add(position, list.get(position));
        notifyDataSetChanged();
    }

    //更新
    public void updataDate(int position) {
        list.set(position, list.get(position));
        notifyItemChanged(position);
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    //定義介面
    public interface RecycleitemClick {
        void OnItemView(View view, int postion);
    }

    //例項化
    public void setRecyclerOnClick(RecycleitemClick click) {
        this.click = click;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView image1;
        TextView text1;

        public MyViewHolder(View itemView, final RecycleitemClick click) {
            super(itemView);

            text1 = itemView.findViewById(R.id.text1);
            image1 = itemView.findViewById(R.id.image1);
            //條目點選事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    click.OnItemView(view, getAdapterPosition());
                }
            });
        }
    }

    class MyViewHolder2 extends RecyclerView.ViewHolder {

        TextView text2;
        ImageView image2;
        ImageView image3;

        public MyViewHolder2(View itemView, final RecycleitemClick click) {
            super(itemView);

            text2 = itemView.findViewById(R.id.text2);
            image2 = itemView.findViewById(R.id.image2);
            image3 = itemView.findViewById(R.id.image3);
            //條目點選事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    click.OnItemView(view, getAdapterPosition());
                }
            });
        }
    }
}

MainActvity

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerViewAdapter recyclerViewAdapter;
    private List<User.DataBean> list=new ArrayList<>();
    private String path="http://www.xieast.com/api/news/news.php?page=1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler);
        Tools tools = new Tools();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.fen));
        recyclerView.addItemDecoration(dividerItemDecoration);
        tools.get(path).setData(new Tools.HttpDate() {
            @Override
            public void getDate(String s) {

                Gson gson = new Gson();
                User user = gson.fromJson(s, User.class);
                list.addAll(user.getData());
                runOnUiThread(new Runnable() {


                    @Override
                    public void run() {
                        recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this,list);
                       recyclerViewAdapter.setRecyclerOnClick(new RecyclerViewAdapter.RecycleitemClick() {
                           @Override
                           public void OnItemView(View view, int postion) {
                               recyclerViewAdapter.updataDate(postion);
                               recyclerViewAdapter.removeDate(postion);
                               recyclerViewAdapter.addDate(postion);
                               Toast.makeText(MainActivity.this,postion+"",Toast.LENGTH_SHORT).show();
                           }
                       });
                        recyclerView.setAdapter(recyclerViewAdapter);
                    }
                });

            }
        });
    }
}

item佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="aaaaa"
        android:textColor="@color/colorAccent" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />
</LinearLayout>

多條目item2

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="bbbb"
        android:textColor="@color/colorPrimary" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />

</LinearLayout>

分割線佈局 在drawable裡建立shape

<?xml version="1.0" encoding="utf-8"?>
<shape
    android:shape="rectangle"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient
        android:type="linear"
        android:startColor="@color/colorAccent"
        />
    <size
        android:height="5dp"
        />
</shape>