为RecyclerView准备一个适配器,并新建LinearAdpater类,让这个适配器继承自RecyclerView.Adapter,并将泛型指定为LinearAdapter.LinearViewHolder。其中LinearViewHolder是我们在LinearAdapter中定义的一个内部类,代码如下:
public class LinearAdapter extends RecyclerView.Adapter<LinearAdapter.LinearViewHolder> {
private Context mContext;
public LinearAdapter(Context context){
this.mContext = context;
}
@Override
public LinearAdapter.LinearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item,parent,false));
}
@Override
public void onBindViewHolder(LinearAdapter.LinearViewHolder holder, final int position) {
holder.textView.setText("哈哈哈哈");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext,"click me..."+position,Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return 30;
}
//LinearViewHolder内部类,传入view参数,view--->LinearRecyclerViewActivity外层布局,通过findViewById()方法获取到TextView
class LinearViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public LinearViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv_title);
}
}
}