初识RecyclerView
2018-09-29 本文已影响4人
萧胜天_
前言
这篇文章先讲述怎么去用,让小白可以根据步骤一步一步的用上RecyclerView,后续会出一系列的文章来分析优缺点,原理,嵌套。
第一步:
1、现在的项目基本上初创建的时候就包含support-v7的包了,如果没有的导入一下;
2、导入RecyclerView 的依赖包,通过File->Project Structure 导入
1.jpg
3、我们就可以开始在xml里面弄个RecyclerView来玩玩啦
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
4、初始化RecyclerView
private RecyclerView mVertical;
private RecyclerView mHorizontal;
private RecyclerView mGrid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVertical = (RecyclerView) findViewById(R.id.vertical);
mHorizontal = (RecyclerView) findViewById(R.id.horizontal);
mGrid = (RecyclerView) findViewById(R.id.grid);
initData();
//ListView 效果
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mVertical.setLayoutManager(linearLayoutManager);
//horizontalScrollView效果
LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
linearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
mHorizontal.setLayoutManager(linearLayoutManager2);
//GridView效果
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
mGrid.setLayoutManager(gridLayoutManager);
}
private void initData() {
datas = new ArrayList<>();
for (int i = 0; i < 102; i++) {
datas.add("测试数据" + (i + 1));
}
}
private class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<String> testDatas;
public Adapter(List<String> testDatas) {
this.testDatas = testDatas;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.item_recycler, parent, false);
return new RecyclerViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
String data = testDatas.get(position);
if (holder instanceof RecyclerViewHolder) {
RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
recyclerViewHolder.getTextView().setText(data);
}
}
@Override
public int getItemCount() {
return testDatas.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public RecyclerViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_textView);
}
public TextView getTextView() {
return textView;
}
}
}
看一下效果图
WechatIMG327.jpeg
很神奇的发现他没有ItemDecoration,就是这个干干净净的,清爽。
不过如果有需要的同学也别着急,可以有多种方式添加,这个留到下一篇文章讲解。