使用RecyclerView实现列表功能
作者:互联网
使用RecyclerView实现列表功能
技术概述
RecyclerView相比ListView而言,封装了viewholder的回收复用,编写Adapter面向的是ViewHolder而不再是View了,复用的逻辑被封装了,写起来更加简单。
技术详述
- 在xml文件中添加RecyclerView控件
- 创建一个item.xml文件,为RecycleView的元素进行布局
- 创建设配器类adapter,该类继承RecyclerView.Adapter
下面介绍相关方法的作用:
ViewHolder():绑定控件
构造方法SubProjectAdapter():初始化列表控件
onCreateViewHolder():创建ViewHolder,返回每一项的布局
onBindViewHolder():将数据和控件绑定
getItemCount():返回Item总条数
public class SubProjectAdapter extends RecyclerView.Adapter<SubProjectAdapter.ViewHolder>{
public ViewHolder(@NonNull View view) {
super(view);
name = (TextView) view.findViewById(R.id.AllTitleTextView);
description = (TextView)view.findViewById(R.id.AllDescriptionTextView);
laucher = (TextView)view.findViewById(R.id.LaucherTextView);
time = (TextView)view.findViewById(R.id.LauchTimeTextView);
}
public SubProjectAdapter(List<SubProject> mSubProjectList) {
this.mSubProjectList = mSubProjectList;
}
@NonNull
@Override
public SubProjectAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.project_item,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull SubProjectAdapter.ViewHolder holder, int position) {
SubProject subProject = mSubProjectList.get(position);
holder.name.setText(subProject.getName());
holder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(subProject.getContext(), MainActivity.class);
intent.putExtra("data",subProject.getJsonObject().toString());
subProject.getContext().startActivity(intent);
}
});
holder.description.setText(subProject.getDescription());
holder.laucher.setText(subProject.getLaucher());
holder.time.setText(subProject.getTime());
}
@Override
public int getItemCount() {
return mSubProjectList.size();
}
}
4.在Activity中,获取RecyclerView对象
5.初始化数据,适配器实例化,设置LayoutManager,设置Adapter
initList();
recyclerView = (RecyclerView)findViewById(R.id.ProjectRecyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(subProjectAdapter);
- 流程图
技术使用中遇到的问题和解决过程
问题:让RecycleView支持上下滑动
解决:外嵌一个ScrollView
进行总结
之前安卓课程中学习过RecycleView的用法,但不够熟练,通过这次实践,加深了对该控件的学习。
参考文献、参考博客
书本《第一行代码》
标签:功能,ViewHolder,holder,列表,subProject,RecyclerView,public,view 来源: https://www.cnblogs.com/fzu-wmz/p/14939643.html