Android实现RecyclerView自定义列表、点击事件以及下拉刷新

qqhhjj 8年前
   <h2>Android使用RecyclerView</h2>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/efb7c229171884f23ca5ddd776b32412.png"></p>    <h3><strong>1. 什么是RecyclerView</strong></h3>    <p>RecyclerView 是 Android-support-v7-21 版本中新增的一个 Widgets,官方对于它的介绍则是:RecyclerView 是 ListView 的升级版本,更加先进和灵活。</p>    <p>简单来说就是:RecyclerView是一种新的视图组,目标是为任何基于适配器的视图提供相似的渲染方式。它被作为ListView和GridView控件的继承者,在最新的support-V7版本中提供支持。</p>    <h3><strong>2. 使用RecyclerView需要掌握什么</strong></h3>    <ul>     <li>Adapter — 包装数据集合并且为每个条目创建视图</li>     <li>LayoutManager — 将每个条目的视图放置于适当的位置</li>     <li>OnItemClickListener — 给每个条目设置点击事件</li>     <li>SwipeRefreshLayout — 给RecyclerView添加下拉刷新事件</li>     <li>ItemAnimator — 在每个条目的视图的周围或上面绘制一些装饰视图</li>     <li>ItemDecoration — 在条目被添加、移除或者重排序时添加动画效果</li>    </ul>    <h3><strong>3. 使用RecyclerView前需要准备什么</strong></h3>    <p>添加依赖包(以Android Studio为例)</p>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/5450f8eb7d398e01dd6271f023c69d19.png"></p>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/e003308faf837b5c5bafb4ce5232e919.png"></p>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/7eba5d58a6eeaf705d6dad21ef7a5a07.png"></p>    <h3><strong>4. 自定义Adapter</strong></h3>    <p>RecyclerView.Adapter包含了一种新型适配器,其实与以前我们使用的适配器基本类似,只是稍微有所不同,比如viewholder它帮我们封装好了,不用像以前使用listview的适配器一样自己去写viewholder了。</p>    <p>Item视图如下:</p>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/a15555eaf50a171da57a2add22250d88.png"></p>    <p>实例代码如下:</p>    <pre>  <code class="language-java">public class RecyclerAdapter extends RecyclerView.Adapter {        private List<Model> models;        public RecyclerAdapter(List<Model> models){          this.models = models;      }        class ViewHolder extends RecyclerView.ViewHolder{            private ImageView picture;          private TextView title,text;            public ViewHolder(View itemView) {              super(itemView);                picture = (ImageView) itemView.findViewById(R.id.picture);              title = (TextView) itemView.findViewById(R.id.title);              text = (TextView) itemView.findViewById(R.id.text);          }            public ImageView getPicture(){              return picture;          }            public TextView getTitle(){              return title;          }            public TextView getText(){              return text;          }      }        @Override      public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {          return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view,null));      }        @Override      public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {            final ViewHolder vh = (ViewHolder) holder;          vh.getPicture().setImageResource(models.get(position).getPicture());          vh.getTitle().setText(models.get(position).getTitle());          vh.getText().setText(models.get(position).getText());      }        @Override      public int getItemCount() {          return models.size();      }  }</code></pre>    <h3><strong>5. LayoutManager有什么作用</strong></h3>    <p>由于RecyclerView已经不单单像以前ListView或者GridView一样,它被作为ListView和GridView控件的继承者,所以在使用它的时候需要通过设置它的LayoutManager去规定它是哪一种类型,另外也可通过设置LayoutManager去设置它是横向还是纵向的列表,以及是否反转。</p>    <p>纵向列表:(第三个参数是设置是否反转,即滑动方向)</p>    <pre>  <code class="language-java">mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);  recyclerview.setLayoutManager(mLayoutManager);</code></pre>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/997df2d46b91311ae6c0e2838ad0d10b.png"></p>    <p>横向列表:</p>    <pre>  <code class="language-java">mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);  recyclerview.setLayoutManager(mLayoutManager);</code></pre>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/d948ccfd8176b3c08e58e2fa31fd72e6.png"></p>    <p>垂直表格布局:</p>    <pre>  <code class="language-java">mLayoutManager = new GridLayoutManager(this,2);  recyclerview.setLayoutManager(mLayoutManager);</code></pre>    <p>水平表格布局:(第四个参数代表是否反转)</p>    <pre>  <code class="language-java">mLayoutManager = new GridLayoutManager(this,2,LinearLayoutManager.HORIZONTAL,false);  recyclerview.setLayoutManager(mLayoutManager);</code></pre>    <p><img alt="这里写图片描述" src="https://simg.open-open.com/show/76e4c13cac011f61ffbade7b2d3081c0.png"></p>    <h3><strong>6. 为什么要自己添加OnItemClickListener</strong></h3>    <p>RecyclerView有一个缺点,在RecyclerView中,没有一个onItemClickListener方法。所以目前在适配器中处理这样的事件比较好。如果想要从适配器上添加或移除条目,需要明确通知适配器。这与先前的notifyDataSetChanged()方法稍微有些不同。具体操作在适配器代码中就可以体现。</p>    <p>具体代码如下:</p>    <pre>  <code class="language-java">public class RecyclerAdapter extends RecyclerView.Adapter {        private List<Model> models;        public RecyclerAdapter(List<Model> models){          this.models = models;      }        class ViewHolder extends RecyclerView.ViewHolder{            private ImageView picture;          private TextView title,text;            public ViewHolder(View itemView) {              super(itemView);                picture = (ImageView) itemView.findViewById(R.id.picture);              title = (TextView) itemView.findViewById(R.id.title);              text = (TextView) itemView.findViewById(R.id.text);          }            public ImageView getPicture(){              return picture;          }            public TextView getTitle(){              return title;          }            public TextView getText(){              return text;          }      }        @Override      public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {          return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view,null));      }        @Override      public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {            final ViewHolder vh = (ViewHolder) holder;          vh.getPicture().setImageResource(models.get(position).getPicture());          vh.getTitle().setText(models.get(position).getTitle());          vh.getText().setText(models.get(position).getText());            //如果设置了回调,就设置点击事件          if (mOnItemClickListener != null){              vh.itemView.setOnClickListener(new View.OnClickListener() {                  @Override                  public void onClick(View v) {                      mOnItemClickListener.onItemClick(vh.itemView,position);                  }              });          }      }        @Override      public int getItemCount() {          return models.size();      }        /** * ItemClick的回调接口 */      public interface OnItemClickListener{          void onItemClick(View view,int position);      }        private OnItemClickListener mOnItemClickListener;        public void setmOnItemClickListener(OnItemClickListener mOnItemClickListener){          this.mOnItemClickListener = mOnItemClickListener;      }  }</code></pre>    <h3><strong>7. 实现下拉刷新与上拉加载更多</strong></h3>    <p>其实跟以前一样,原生的ListView或者GridView都不能满足实际App的需要,很多时候都要通过自定义View去实现列表的下拉刷新和上拉加载,RecyclerView也是一样,不过这里不会介绍如何去自定义RecyclerView,相反,我们会借用SwipeRefreshLayout这个组件,更快地去实现列表刷新功能</p>    <p>界面布局如下:</p>    <pre>  <code class="language-java"><view          android:id="@+id/swipeRefreshLayout"          class="android.support.v4.widget.SwipeRefreshLayout"          android:layout_width="match_parent"          android:layout_height="match_parent">            <android.support.v7.widget.RecyclerView              android:id="@+id/recyclerview"              android:layout_width="match_parent"              android:layout_height="match_parent">            </android.support.v7.widget.RecyclerView>    </view></code></pre>    <p>设置下拉刷新监听事件:</p>    <pre>  <code class="language-java">swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);  swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {              @Override              public void onRefresh() {                  //重新获取数据                  //获取完成swipeRefreshLayout.setRefreshing(false);              }  });</code></pre>    <p>设置上拉加载更多可以通过设置滑动监听事件来实现:</p>    <pre>  <code class="language-java">recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {              @Override              public void onScrollStateChanged(RecyclerView recyclerView, int newState) {                  super.onScrollStateChanged(recyclerView, newState);                  if (newState == RecyclerView.SCROLL_STATE_IDLE                          && lastVisibleItem + 1 == adapter.getItemCount()) {                      swipeRefreshLayout.setRefreshing(true);                        //分页获取数据                      //获取完成swipeRefreshLayout.setRefreshing(false);                  }              }                @Override              public void onScrolled(RecyclerView recyclerView, int dx, int dy) {                  super.onScrolled(recyclerView, dx, dy);                  lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();              }          });</code></pre>    <h3><strong>8. ItemAnimator 与ItemDecorator</strong></h3>    <p>由于RecyclerView里没有自带分割线,所以就出现了ItemDecorator,但其实还有另外一种方法,就是直接在Item界面布局中添加分割线,这样可以省去很多代码;<br> 而ItemAnimator简单来说是会根据适配器上收到的相关通知去动画的显示组件的修改,添加和删除等。它会自动添加和移除item的动画。自带的默认效果也不错,已经非常好了。因为这两项不是很常用,所以这里就不多加介绍了,有兴趣的同学可以上网找详细的资料学习。</p>    <p>来自: http://blog.csdn.net/u014756589/article/details/51280659</p>    <p> </p>