新闻模块——RecyclerView

一、知识点:

  1. 用处
  • 1.实现新闻列表展示
  • 2.列表添加分割线
  • 3.列表添加入场动画
  • 4.实现切换不同展示效果(列表,网格,瀑布)
  • 5.实现多布局展示新闻列表 6.实现item点击事件

        2.意义

  • RecyclerView 兼顾了灵活性和个性化,是功能强大的工具
  • 特点一:支持瀑布流
  • 特点二:支持三种布局
  • 特点三:支持item动画

recyclerview的基本使用

recyclerview的特点

  • 支持多布局
  • 支持瀑布流
  • 支持分割线
  • 支持动画
  • 自动复用

如何实现recyclerview

  1. 1添加依赖
  2. 2自定义类继承自RecyclerView.Adapter
  3. 3实现未实现的方法
  •  getitemCount:返回个数
  • onCreateViewHolder:创建viewholder
  • onBindViewHolder:绑定数据

      4.setAdaoter初始化适配器,设置适配器

****  环境复杂度

  • 环境复杂度:使用recyclerview时考虑未读取到数据时的情况 解决方案:未读到数据时适配要做空数据保护(if是否=0),避免程序崩溃,并且在页面没数据 时给出提示来优化用户体验
  • 环境复杂度:可能会遇到控件不显示数据的情况 解决方案:网络获取数据正常但界面不显示考虑是否添加适配器
  • 环境复杂度:RecyclerView优化:分页拉取网络数据 解决方案:设置参数pageNum来实现分页,每次加载一定数量的数据,避免数据 量过大导致程序未响应或等待
  • 环境复杂度:可以以不同的形式展示数据(列表,瀑布流等) 解决方案:设置控件不同的参数来实现不同的展示效果
  • 环境复杂度:解决子控件需要做事件处理的情况 解决方案:适配器中给子控件添加事件监听,并正常实现数据传递
  • 环境复杂度:列表切换考虑切换动画的流畅性和优化 解决方案:列表加载时添加入场动画
  • 环境复杂度:子控件需要做事件处理的情况 解决方案:在万能适配器中给子控件添加事件监听,并正常实现数据传递
  • 环境复杂度:万能适配器编写—recycleview加载其他用户评论 解决方案:从服务器获取数据,使用BaseRecyclerViewAdapterHelper给recycleview适配数据
  • 环境复杂度:万能适配器优化—实现评论多布局 解决方案:recycleview多布局嵌套
  • 环境复杂度:实现用户评论功能 解决方案:用户评论当前后更新适配器,刷新页面数据

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;

    MyBaseQAdapter myBaseQAdapter;
    List dataList=new ArrayList();
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        recyclerView = (RecyclerView) findViewById(R.id.re);
        // 准备数据源
        initdata();
        // 定义适配器
         myBaseQAdapter=new MyBaseQAdapter(R.layout.item,dataList,this);
        // 设置适配器
        recyclerView.setAdapter(myBaseQAdapter);
        //线性布局
       // recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //网格布局
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
//        recyclerView.setLayoutManager(gridLayoutManager);
        //瀑布流
        StaggeredGridLayoutManager staggeredGridLayoutManager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        //水平线
//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL);
//        dividerItemDecoration.setDrawable(getDrawable(R.drawable.dv1));
//        recyclerView.addItemDecoration(dividerItemDecoration);
        //垂直线
        DividerItemDecoration dividerItemDecoration1 = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        dividerItemDecoration1.setDrawable(getDrawable(R.drawable.dv));
        recyclerView.addItemDecoration(dividerItemDecoration1);
        //动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setRemoveDuration(2000);
        defaultItemAnimator.setAddDuration(1000);
        defaultItemAnimator.setChangeDuration(2000);
        recyclerView.setItemAnimator(defaultItemAnimator);
        //点击图片消失
        myBaseQAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                dataList.remove(position);
                myBaseQAdapter.notifyItemRemoved(position);
            }
        });
        //滑动
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                //左右滑动
                int x=ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
                return makeMovementFlags(0,x);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return true;//true
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                //滑动删除
                int position =viewHolder.getPosition();
                dataList.remove(position);
                myBaseQAdapter.notifyItemRemoved(position);
            }
        });
        itemTouchHelper.attachToRecyclerView(recyclerView);

        //第三个环境复杂度 (子控件点击事件)
        myBaseQAdapter.addChildClickViewIds(R.id.imageView);
        myBaseQAdapter.addChildClickViewIds(R.id.textView);
        myBaseQAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                int id=view.getId();
                switch(id){
                    case R.id.imageView:
                        Toast.makeText(MainActivity.this, "你点击了图片", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.textView:
                        Toast.makeText(MainActivity.this, "点击文本", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        
   // 添加轮播图
        View view = LayoutInflater.from(this).inflate(R.layout.head,null);
        myBaseQAdapter.addHeaderView(view);
        Banner banner = view.findViewById(R.id.banner);

        List images = new ArrayList<>();
        OkGo.get("http://43.143.146.165:7777/banner/json").execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                String body = response.body().toString();
                Log.d("--ban","asd"+body);

                List data = new Gson().fromJson(body, BanBean.class).getData();

                for (int i=0; iget("http://43.143.146.165:7777/foods/getFoods?pageSize=10¤tPage=1").execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                String body = response.body().toString();
                Log.i("asd",body);

                List data = new Gson().fromJson(body, FoodBean.class).getData();

                if (dataList.size()==0&&dataList==null){
                    Toast.makeText(MainActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }
                else {
                    dataList.addAll(data);
                    myBaseQAdapter.notifyDataSetChanged();

                }
            }
        });
    }
}

BanBean http://43.143.146.165:7777/banner/json

FoodBean http://43.143.146.165:7777/foods/getFoods?pageSize=10¤tPage=1

适配器

public class MyBaseQAdapter extends BaseQuickAdapter {
    Context context;

    public MyBaseQAdapter(int layoutResId, @Nullable List data, Context context) {
        super(layoutResId, data);
        this.context = context;
    }

    @Override
    protected void convert(BaseViewHolder baseViewHolder, FoodBean.DataDTO dataDTO) {
        baseViewHolder.setText(R.id.textView,dataDTO.getTitle());
        ImageView view = baseViewHolder.getView(R.id.imageView);
        Glide.with(context).load(dataDTO.getPic()).override(200).into(view);
    }

}

 左右联动

先看布局



    
    


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

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

public class MainActivity2 extends AppCompatActivity {
    private RecyclerView recyclerView1,recyclerView2;

    List dataDTOList11=new ArrayList<>();
    List shopList=new ArrayList<>();

    MyBQ1Adapter myBQ1Adapter;
    MyBQ2Adapter myBQ2Adapter;
    int id=14;
    int page=1;
    List dataDTO1;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        初始化控件
        recyclerView1 = (RecyclerView) findViewById(R.id.rc1);
        recyclerView2 = (RecyclerView) findViewById(R.id.rc2);
        // 准备数据源
        OkGo.get("http://43.143.146.165:7777/goods/category").execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                String body = response.body().toString();
                Log.d("--asd","asd: " + body);
                List data = new Gson().fromJson(body, ShopTypeBean.class).getData();
                for (int i = 0; i < data.size(); i++) {
                    //再次解
                    List dataDTO1s = data.get(i).getData();
                    dataDTOList11.addAll(dataDTO1s);

                }
                myBQ1Adapter.notifyDataSetChanged();
            }
        });
        // 定义适配器
        myBQ1Adapter=new MyBQ1Adapter(R.layout.item,dataDTOList11);
        // 设置适配器
        recyclerView1.setAdapter(myBQ1Adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recyclerView1.setLayoutManager(linearLayoutManager);

        initData();
        // 设置适配器
        myBQ2Adapter=new MyBQ2Adapter(R.layout.item,shopList,this);
        recyclerView2.setAdapter(myBQ2Adapter);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
        linearLayoutManager2.setOrientation(RecyclerView.VERTICAL);
        recyclerView2.setLayoutManager(linearLayoutManager2);

        //点击适配器
        myBQ1Adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                id=dataDTOList11.get(position).getId();
                page=1;
                shopList.clear();
                initData();


            }
        });
    }
    public void initData() {
        OkGo.get("http://43.143.146.165:7777/goods/info?category_id="+id+"¤tPage="+page+"&pageSize=10").execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                String body = response.body().toString();
                Log.d("--asd1","asd: " + body);
                List data1 = new Gson().fromJson(body, ShopBean.class).getData();
                shopList.addAll(data1);
                myBQ2Adapter.notifyDataSetChanged();
            }
        });

    }
}

 适配器



import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.util.List;

public class MyBQ1Adapter extends BaseQuickAdapter {


    public MyBQ1Adapter(int layoutResId, @Nullable List data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, ShopTypeBean.DataDTO.DataDTO1 dataDTO) {
       baseViewHolder.setText(R.id.textView,dataDTO.getCategory_name());
    }
}



import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.util.List;

public class MyBQ2Adapter extends BaseQuickAdapter {
  Context context;
    public MyBQ2Adapter(int layoutResId, @Nullable List data,Context context) {
        super(layoutResId, data);
        this.context=context;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, ShopBean.DataDTO dataDTO) {
        baseViewHolder.setText(R.id.textView,dataDTO.getGoods_desc());
        ImageView imageView = baseViewHolder.getView(R.id.imageView);
        Glide.with(context).load(dataDTO.getGoods_default_icon()).into(imageView);
    }
}

左右视图



    

新闻模块——RecyclerView_第1张图片



import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

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

public class MainActivity3 extends AppCompatActivity {
    private RecyclerView rc3;
    List dataList=new ArrayList<>();
    MyBQMultiAdapter myBQMultiAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        //初始化控件
        rc3 = (RecyclerView) findViewById(R.id.rc3);
        //准备数据源
        OkGo.get("http://43.143.146.165:7777/foods/getFoods?pageSize=10¤tPage=1").execute(new StringCallback() {
            @Override
            public void onSuccess(Response response) {
                String body = response.body().toString();
                Log.d("--asd3","asd: " + body);
                List data = new Gson().fromJson(body, FoodBean.class).getData();
                dataList.addAll(data);
                for (int i = 0; i < dataList.size(); i++) {
                    int type=(i%2==0)?0:1;
                    dataList.get(i).setType(type);
                }
                myBQMultiAdapter.notifyDataSetChanged();

            }
        });
        //定义适配器
        myBQMultiAdapter = new MyBQMultiAdapter(dataList, this);
        // 设置适配器
        rc3.setAdapter(myBQMultiAdapter);
        rc3.setLayoutManager(new LinearLayoutManager(this));

    }
}

 适配器



import android.content.Context;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.util.List;

public class MyBQMultiAdapter extends BaseMultiItemQuickAdapter {
    Context context;

    public MyBQMultiAdapter(@Nullable List data,Context context) {
        super(data);
        this.context = context;
        addItemType(0,R.layout.item);
        addItemType(1,R.layout.item2);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, FoodBean.DataDTO dataDTO) {
        if (dataDTO.getItemType()==0)
        {
            baseViewHolder.setText(R.id.textView,dataDTO.getTitle());
            ImageView imageView = baseViewHolder.getView(R.id.imageView);
            Glide.with(context).load(dataDTO.getPic()).override(200,200).into(imageView);
        }else {
            baseViewHolder.setText(R.id.textView3,dataDTO.getTitle());
            ImageView imageView = baseViewHolder.getView(R.id.imageView3);
            Glide.with(context).load(dataDTO.getPic()).override(200,200).into(imageView);
        }
    }
}

item  

新闻模块——RecyclerView_第2张图片新闻模块——RecyclerView_第3张图片

你可能感兴趣的:(阶段学习,动画)