RecyclerView学习笔记1_入门

一、 前言

RecyclerView是谷歌V7包下新增的控件,用来替代ListView、GridView的使用.

�要点:
  • LayoutManager:布局管理器,目前SDK中提供了三种自带的LayoutManager:
    LinearLayoutManager-----类似ListView
    GridLayoutManager-----类似GridView
    StaggeredGridLayoutManager-----瀑布流
  • ItemDecoration:Item间的分割线样式
  • ItemAnimator:Item增加、删除的动画
  • 点击、长按事件:比较麻烦

二、开发环境

  • IDE: Android Studio 2.0 Beta 6
  • SDK: Android 23

三、使用

�配置:build.gradle
dependencies {
    ...
    compile 'com.android.support:recyclerview-v7:23.1.1'
}
�主布局文件:activity_main.xml



�子布局文件:rv_item_book.xml



�ViewHolder文件:BookViewHolder
public class BookViewHolder extends RecyclerView.ViewHolder {
​
   public TextView tvBook;
​
   public BookViewHolder(View view) {
       super(view);
       tvBook = (TextView) view.findViewById(R.id.tv_book);
   }
}
�适配器:BookRecyclerViewAdapter
public class BookRecyclerViewAdapter extends RecyclerView.Adapter {
​
   private LayoutInflater mLayoutInflater;
   private Context mContext;
   private String[] mBooks;
​
   public BookRecyclerViewAdapter(Context context, String[] mBooks) {
       this.mBooks = mBooks;
       this.mContext = context;
       mLayoutInflater = LayoutInflater.from(context);
   }
​
   @Override
   public BookViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       // 创建一个View
       View view = mLayoutInflater.inflate(R.layout.rv_item_book, parent, false);
       // 创建一个ViewHolder
       BookViewHolder bookViewHolder = new BookViewHolder(view);
       return bookViewHolder;
   }
​
   @Override
   public void onBindViewHolder(BookViewHolder holder, int position) {
       // 绑定数据到ViewHolder上
       holder.tvBook.setText(mBooks[position]);
   }
​
   @Override
   public int getItemCount() {
       // item数量
       return mBooks.length;
   }
}
�主界面:MainActivity
public class MainActivity extends AppCompatActivity {
    private RecyclerView rebook;
    private String[] mBooks = {"认知盈余", "和喜欢的一切在一起", "从0到1", "从你的全世界路过", "打工旅行", "番茄工作法图解"}; 
        
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 
        rvBook = (RecyclerView) findViewById(R.id.rv_book); 

        // 1. 这里用线性显示,类似于ListView 
        rvBook.setLayoutManager(new LinearLayoutManager(this)); 

        // 2. 这里用线性宫格显示,类似于GridView
//      rvBook.setLayoutManager(new GridLayoutManager(this, 2)); 

        // 3. 这里用线性宫格显示,类似于瀑布流
//      rvBook.setLayoutManager(new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL)); 

        rvBook.setAdapter(new BookRecyclerViewAdapter(MainActivity.this, mBooks)); 
    }
}

四、总结

RecyclerView的另一个特点是标准化了 ViewHolder, 编写Adapter面向的是ViewHolder而不在是View了, 复用的逻辑被封装了, 写起来更加简单。

你可能感兴趣的:(RecyclerView学习笔记1_入门)