學習了ListView控件之後,接着開始了RecyclerView控件的探索,在學習得過程中發現了些不理解的問題,貼出代碼和問題做些記錄。
- 這是RecyclerView的適配器部分
- 沒有貼出的部分有Brother類(定義了照片和姓名)
- 主佈局和子項佈局
- 主方法
public class BrotherAdapter extends RecyclerView.Adapter<BrotherAdapter.ViewHolder> {
private List<Brother> mBrotherList;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView brotherPicture;
TextView brotherDescription;
public ViewHolder(View view) {
super(view);
brotherPicture = (ImageView)view.findViewById(R.id.brother_picture);
brotherDescription = (TextView)view.findViewById(R.id.brother_description);
}
}
public BrotherAdapter(List<Brother> brotherList) {
mBrotherList = brotherList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//返回的類型爲RecyclerView.ViewHolder和爲ViewHolder有什麼不同?
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.brother_item,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
public void onBindViewHolder(ViewHolder holder, int position) {
Brother brother = mBrotherList.get(position);
holder.brotherPicture .setImageResource(brother.getImageId());
holder.brotherDescription.setText(brother.getName());
}
@Override
public int getItemCount() {
return mBrotherList.size();
}
}