

本帖最后由 玩不坏的小黑 于 2016-5-10 10:25 编辑
RecyclerView使用教程前两个星期用到只学习了使用方法,没完全理解,这次用就做个教程用于学习
第一步:引用Recyclerview 包在gradle文件里面添加<span style="line-height: 1.5; background-color: rgb(255, 255, 255);">dependencies {</span><span style="line-height: 1.5; background-color: rgb(255, 255, 255);"> compile'com.android.support:recyclerview-v7:23.1.1'</span>
<span style="line-height: 1.5; background-color: rgb(255, 255, 255);">}</span>
第二步:在XMl里面添加Recyclerview<android.support.v7.widget.RecyclerViewandroid:id="@+id/recyclerview"android:layout_width="match_parent"android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
第三步:在activity里面findViewById()recyclerView.findViewById(R.id.recyclerview);第四步:设置布局管理器,布局管理器待会再详细研究recyclerView.setLayoutManager(new LinearLayoutManager(this));第五步:新建一个适配器package com.xiaohei.recyclerview;import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xiaohei on 2016/5/5.
*/
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List *本站禁止HTML标签噢* Items;
public RecyclerviewAdapter() {
Items = new ArrayList<>();
for(int i = 0 ; i<100;i++){
Items.add("小黑 " + i);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,null);
RecyclerView.ViewHolder holder= new xiaoheiHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
xiaoheiHolder XHolder = (xiaoheiHolder) holder;
XHolder.mTextView.setText(Items.get(position));
}
@Override
public int getItemCount() {
return Items.size();
}
class xiaoheiHolder extends RecyclerView.ViewHolder{
TextView mTextView;
public xiaoheiHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.item_id);
}
}
}
recyclerview的适配器流程是这样的首先:getCount 获取到元素个数然后创建view{创建view的时候要用parent获取到item的view,然后new一个Holderitem的view要写一个新的layout文件@Overridepublic RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item,null);
RecyclerView.ViewHolder holder= new xiaoheiHolder(view);
return holder;
}
然后return holder}然后再绑定{绑定的时候就是填充数据第六步:在activity里面给recyclerview设置适配器recyclerView.setAdapter(new RecyclerviewAdapter());然后运行就可以看到这个界面:
基础部分就先记这么多
recyclerview的灵活性远不止这样
找时间记录下布局管理器和然后还有一个ViewType的使用