一、RecycleViewActivity
/** * RecycleView+recycleView.Adapter+RecycleView.ViewHolder */ public class RecycleViewActivity extends AppCompatActivity { private List<DataModel> models; private RecyclerView mRecyclerView; private RecycleAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycle_view); initView(); } /** * 初始化 */ private void initView() { getData(); mRecyclerView = (RecyclerView) findViewById(R.id.rv_container); mRecyclerView.setLayoutManager(new GridLayoutManager(this,3)); adapter = new RecycleAdapter(models); mRecyclerView.setAdapter(adapter); } /** * 构建模拟数据 */ private void getData() { models = new ArrayList<>(); DataModel model; for (int i = 0; i < 20; i++) { model = new DataModel("列表标题" + i, "说明文字" + i); models.add(model); } } }
二RecycleAdapter
/** * RecyclerView.Adapter * 三个方法,外加一个构造方法 * Created by Devin Chen on 2016/12/17. */ public class RecycleAdapter extends RecyclerView.Adapter<RecycleViewHolder> implements View.OnClickListener { private Context context; private List<DataModel> dataModels; public RecycleAdapter(List<DataModel> dataModels) { this.dataModels = dataModels; } @Override public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { this.context = parent.getContext(); View view = LayoutInflater.from(context).inflate(R.layout.item_data_model, null); //RecyclerView没有setOnItemClickListener监听,所以可以在这里写,也可以在ViewHolder里面写 //但是这里不能获取position //所以可以在这里把view交给一个属性,在onBindViewHolder里面去设置监听 view.setOnClickListener(this); return new RecycleViewHolder(context, view); } @Override public void onBindViewHolder(RecycleViewHolder holder, int position) { holder.setItem(dataModels.get(position)); holder.refreshView(); } @Override public int getItemCount() { return dataModels.size(); } @Override public void onClick(View v) { } }
三、RecycleViewHolder
/** * RecyclerView.ViewHolder * 跟BaseAdapter的ViewHolder写法基本一样 * Created by Devin Chen on 2016/12/17. */ public class RecycleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Context context; private ImageView icon; private TextView title,desc; private DataModel item; public RecycleViewHolder(Context context,View itemView) { super(itemView); this.context=context; icon= (ImageView) itemView.findViewById(R.id.img_icon); title= (TextView) itemView.findViewById(R.id.txt_title); desc= (TextView) itemView.findViewById(R.id.txt_desc); //RecyclerView没有setOnItemClickListener监听,所以可以在这里写 //用getAdapterPosition()可以获取position itemView.setOnClickListener(this); } public void setItem(DataModel item) { this.item = item; } public void refreshView(){ icon.setImageResource(R.mipmap.ic_launcher); title.setText(item.getTitle()); desc.setText(item.getDesc()); } @Override public void onClick(View v) { } }