MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mMyAdapter;
private LinearLayoutManager mLayoutManager;
private List<String> list;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
mRecyclerView = findViewById(R.id.recycler_view);
mMyAdapter = new MyAdapter(list);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mMyAdapter);
}
private void initData() {
list = new ArrayList<>();
for (int i = 0; i <= 20; i++) {
list.add("Item " + i);
}
}
}
Adapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
//数据源
private List<String> mList;
public MyAdapter(List<String> list) {
mList = list;
}
//返回item个数
@Override
public int getItemCount() {
return mList.size() ;
}
//创建ViewHolder
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new NormalHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
//填充视图
@Override
public void onBindViewHolder(@NonNull final MyAdapter.ViewHolder holder, final int position) {
holder.mView.setText(mList.get(position));
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView.findViewById(R.id.text_view);
}
}
}