public class LinearRecyclerViewActivity extends AppCompatActivity {
RecyclerView mRvMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_recycler_view);
mRvMain= findViewById(R.id.rv_main);
LinearLayoutManager manager = new LinearLayoutManager(this); //LinearRecyclerViewActivity.this
mRvMain.setLayoutManager(manager);
mRvMain.setAdapter(new LinearAdapter());
}
}
二 Adapter
public class LinearAdapter extends RecyclerView.Adapter <LinearAdapter.LinearViewHolder>{//一、这里是后面自己定义的holder
@NonNull
@Override
//一、因为返回值是RecyclerView.ViewHolder(因为LinearViewHolder是ViewHolder的子类,所以直接使用linearviewholder)我们就要new一个ViewHolder作为返回值,因为没有类所有就新建一个LinearViewHolder(下面第三步),并创建对象
public LinearAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_linear_item,parent,false);
return new LinearViewHolder(view); //二、LinearViewHolder类构造函数需要一个view对象 就必须传入View对象,并且所以使用打气筒将显示item,inflate将XML文件转换成View对象,赋值给新建对象
}
@Override
public void onBindViewHolder(LinearAdapter.LinearViewHolder holder, int position) {
holder.mtv.setText("你好"+position );
}
@Override
public int getItemCount() {
return 20;
}
////////自己定义的Holder///////////
//三、
class LinearViewHolder extends RecyclerView.ViewHolder
{
private TextView mtv;
public LinearViewHolder(@NonNull View itemView) { //itemView 的值是 开头onCreateViewHolder传出的值
super(itemView);
mtv=itemView.findViewById(R.id.tv_tile);
}
}
}
LinearRecyclerViewActivity.this