recycleview自定义布局
时间: 2023-10-04 19:06:25 浏览: 96
自定义Recycleview
可以使用 RecyclerView.Adapter 来自定义 RecyclerView 的布局。您需要创建一个继承自 RecyclerView.ViewHolder 的类来保存布局的视图,并在 RecyclerView.Adapter 中使用 onCreateViewHolder() 方法创建视图。然后,在 onBindViewHolder() 方法中使用视图来填充数据。这是一个简单的例子:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public MyViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.textview);
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_layout, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
阅读全文