Android学习笔记

Android--更加强大的滚动控件 RecyclerView

2017-12-10  本文已影响0人  Mason_Xu

更加强大的滚动控件 RecyclerView #P123

基本用法

新建FruitAdapter

  1. 定义内部类ViewHoler ,继承自RecyclerView.ViewHolder
  2. ViewHoler的构造函数传入一个View参数,这个参数通常就是RecyclerView子项的最外层布局,通过findViewById() 方法来获取布局中的Imageiew和TextView的实例
  3. FruitAdapter 中也有构造函数,这个方法用于把要展示的数据源传进来,并赋值给一个全部变量mFruitList
  4. FruitAdapter继承自RecyclerView.Adapter,所以要重写onCreatViewHolder(),onBingViewHolder(),getItemCount()
    1. onCreatViewHolder()用来创建ViewHolder实例,将fruit_item布局加载进来,然后创建一个ViewHoler实例,并把加载出来的布局传入构造函数中,最后将ViewHoler的实例返回
    2. onBingViewHolder()用于对RecyclerView子项的数据进行赋值,会在每个子项被滚动到屏幕内的时候执行,通过position 参数得到当前项的Fruit实例,然后将数据设置到ViewHolder的ImageView和TextView当中即可
    3. getItemCount() 告诉RecyclerView有多少子项 ,返回 mFruitList.size()
    public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
      private List<Fruit> mFruitList;
    
      /**
       * Created by Mason on 2017/11/16.
       */
    
      static class ViewHolder extends RecyclerView.ViewHolder {
          ImageView fruitImage;
          TextView fruitName;
    
          public ViewHolder(View view) {
              super(view);
              fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
              fruitName = (TextView) view.findViewById(R.id.fruit_name);
          }
        }   
    
      public FruitAdapter(List<Fruit> fruitList) {
    
          mFruitList = fruitList;
      }
    
      @Override
      public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
          View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
          ViewHolder holder = new ViewHolder(view);
          return holder;
      }
    
      @Override
      public void onBindViewHolder(ViewHolder holder, int position) {
          Fruit fruit = mFruitList.get(position);
          holder.fruitImage.setImageResource(fruit.getImageId());
          holder.fruitName.setText(fruit.getName());
      }
    
      @Override
      public int getItemCount() {
          return mFruitList.size();
      }
    }
    

改变为横向RecyclerView

RecyclerView 点击事件

上一篇下一篇

猜你喜欢

热点阅读