RecyclerView 列表简单用法
新建文件:RecyclerList类名
public class RecyclerList { private String title; private String rate; public RecyclerList(){ } private RecyclerList(String title, String rate) { this.title = title; this.rate = rate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } }
新建文件:RecyclerViewAdapter适配器
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { private List<RecyclerList> mList; public RecyclerAdapter(List<RecyclerList> list) { mList = list; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_recycler_item,viewGroup,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { RecyclerList listItem = mList.get(i); viewHolder.mTitle.setText(listItem.getTitle()); viewHolder.mRate.setText(listItem.getRate()); } @Override public int getItemCount() { return mList.size(); } static class ViewHolder extends RecyclerView.ViewHolder{ View itemView; TextView mTitle; TextView mRate; public ViewHolder(View view) { super(view); itemView = view; mTitle = (TextView) view.findViewById(R.id.title); mRate = (TextView) view.findViewById(R.id.rate); } } }
activity里面代码
public class recyclerViewActivity extends AppCompatActivity { private RecyclerView recyclerView; private List<RecyclerList> mList = new ArrayList<>(); private LinearLayoutManager layoutManager; private RecyclerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); RecyclerList item1 = new RecyclerList(); item1.setTitle("小偷家族"); item1.setRate("8.7"); mList.add(item1); RecyclerList item2 = new RecyclerList(); item2.setTitle("蜘蛛侠:平行宇宙"); item2.setRate("8.7"); mList.add(item2); RecyclerList item3 = new RecyclerList(); item3.setTitle("三次元女友"); item3.setRate("6.1"); mList.add(item3); RecyclerList item4 = new RecyclerList(); item4.setTitle("悠哉日常大王剧场版:假期活动"); item4.setRate("8.9"); mList.add(item4); adapter = new RecyclerAdapter(mList); recyclerView.setAdapter(adapter); } }