首先点击file-->project-->选中新创建的工程-->dependencies-->点击“+”号-->选中第一个-->找到recyclerview-v7 (com.android.support:recyclerview-v7:25.3.1)-->ok
接着创建布局:
<android.support.v7.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="match_parent" />
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
List<String> list=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv= (RecyclerView) findViewById(R.id.rv);
//模拟假数据
for(int i=0;i<100;i++){
list.add("条目"+i);
}
LinearLayoutManager manager=new LinearLayoutManager(this);
rv.setLayoutManager(manager);
//创建适配器
MyAdapter adapter=new MyAdapter();
rv.setAdapter(adapter);
//设置点击事件
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void OnItemClick(View view, int position) {
Toast.makeText(MainActivity.this,"------"+position,Toast.LENGTH_LONG).show();
}
});
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
//利用接口回调实现点击事件
OnItemClickListener listener;
public void setOnItemClickListener(OnItemClickListener listener){
this.listener=listener;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//加载布局
View view=View.inflate(MainActivity.this,R.layout.item,null);
//每次点击时都会调用此方法
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//有可能传过来的listener为null
if(listener!=null){
//view为每次点击时的条目
//view.getTag()获得条目下标position
listener.OnItemClick(view,(int)view.getTag());
}
}
});
//返回加载的视图
return new LeftViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//为每个条目赋值
((LeftViewHolder)holder).tv.setText(list.get(position));
//把条目的下标position设置给holder
holder.itemView.setTag(position);
}
@Override
public int getItemCount() {
//用三元表达式 如果集合list为空的话返回数目为零否则返回集合数目
return list!=null?list.size():0;
}
public class LeftViewHolder extends RecyclerView.ViewHolder{
TextView tv;
public LeftViewHolder(View itemView) {
super(itemView);
tv=itemView.findViewById(R.id.tv);
}
}
}
public interface OnItemClickListener{
public void OnItemClick(View view,int position);
}
}