使用资源文件自定义列表项就相当于ios中使用xib自定义tableView的cell。
首先是创建xml文件,之后是创建RecyclerView.Adapter,就相当于Cell。xml文件和这个MyAdapter关联,就是一个Cell。
class MyAdapter extends RecyclerView.Adapter {
class ViewHolder extends RecyclerView.ViewHolder {
private View root;
private TextView tvTitle,tvContent;
public ViewHolder(View root) {
super(root);
tvTitle = (TextView)root.findViewById(R.id.tvTitle);
tvContent = (TextView)root.findViewById(R.id.tvContent);
}
public TextView getTvTitle() {
return tvTitle;
}
public void setTvTitle(TextView tvTitle) {
this.tvTitle = tvTitle;
}
public TextView getTvContent() {
return tvContent;
}
public void setTvContent(TextView tvContent) {
this.tvContent = tvContent;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_cell,null));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHolder vh = (ViewHolder) holder;
CellData cd = data[position];
vh.getTvTitle().setText(cd.title);
vh.getTvContent().setText(cd.content);
}
@Override
public int getItemCount() {
return data.length;
}
private CellData[] data = new CellData[]{new CellData("极客学院","IT职业教育"),new CellData("新闻","这个新闻真不错")};
}
这个时候可以创建一个class,相当于ios里面的model。
public class CellData {
public CellData(String title,String content){
this.title = title;
this.content = content;
}
public String title = "title";
public String content = "content";
}
其实数据的处理都放在了Adapter里面了,使用的时候就很方便了。
public class MainActivity extends AppCompatActivity {
private RecyclerView rv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rv = new RecyclerView(this);
setContentView(rv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(new MyAdapter());
}
}
只需要添加RecyclerView以及配置就行。