RecyclerView 使用Adapter中的配置和Acticity的寫法
阿新 • • 發佈:2019-01-27
RecyclerView Adapter中的設定
public class HomePageFiledAdapter extends RecyclerView.Adapter {
private Context mContext;
private List<HomePageListBean.AreaMenuListBean.ChildAreaBean> list;
public HomePageFiledAdapter(Context context, List<HomePageListBean.AreaMenuListBean.ChildAreaBean> list) {
this .list = list;
this.mContext = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_homepage, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// ((MyViewHolder)holder).itemView.set
((MyViewHolder)holder).itemView.setTag(position);
((MyViewHolder)holder).name.setText(list.get(position).getAreaName());
}
@Override
public int getItemCount () {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView icon;
private TextView name;
public MyViewHolder(View itemView) {
super(itemView);
icon= (ImageView) itemView.findViewById(R.id.item_homepage_icon);
name= (TextView) itemView.findViewById(R.id.item_homepage_name);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
onClickItemListener.onClickItem((Integer) v.getTag());
}
}
public void setOnClickItemListener(Mypageradapter.OnClickItemListener onClickItemListener){
this.onClickItemListener=onClickItemListener;
}
public Mypageradapter.OnClickItemListener onClickItemListener;
public interface OnClickItemListener{
void onClickItem(int position);
};
在Activity中新增方法
private void initFiled() {
HomePageFiledAdapter adapter = new HomePageFiledAdapter(this,
mHomePageListBean.getAreaMenuList().get(0).getChildArea());
filedRecyclerView.setLayoutManager(new LinearLayoutManager(context));
filedRecyclerView.setAdapter(adapter);
adapter.setOnClickItemListener(new Mypageradapter.OnClickItemListener() {
@Override
public void onClickItem(int position) {
Intent it = new Intent(mContext, FirstDetailActivity.class);
it.putExtra("name", Bean.getAreaMenuList().get(0).getAreaName());
it.putExtra("id", Bean.getAreaMenuList().get(0).getChildArea().get(position).getId());
startActivity(it);
}
});
}