RecyclerView相比ListView而言,封装了viewholder的回收复用,编写Adapter面向的是ViewHolder而不再是View了,复用的逻辑被封装了,写起来更加简单。
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的用法,但不够熟练,通过这次实践,加深了对该控件的学习。
书本《第一行代码》