在RecyclerView中使用适配器类给出序列号,可以通过以下步骤实现:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<DataModel> mDataList;
// 构造函数传入数据列表
public MyAdapter(List<DataModel> dataList) {
mDataList = dataList;
}
// 创建ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
// 绑定ViewHolder
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
DataModel data = mDataList.get(position);
holder.bindData(data, position);
}
// 返回数据项数量
@Override
public int getItemCount() {
return mDataList.size();
}
// ViewHolder定义
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mSerialNumberTextView;
private TextView mDataTextView;
public ViewHolder(View itemView) {
super(itemView);
mSerialNumberTextView = itemView.findViewById(R.id.serial_number_text_view);
mDataTextView = itemView.findViewById(R.id.data_text_view);
}
public void bindData(DataModel data, int position) {
// 设置序列号
mSerialNumberTextView.setText(String.valueOf(position + 1));
// 设置数据
mDataTextView.setText(data.getData());
}
}
}
item_layout.xml
的布局文件,其中包含一个显示序列号的TextView和一个显示数据的TextView。<!-- item_layout.xml -->
<LinearLayout
...
>
<TextView
android:id="@+id/serial_number_text_view"
... />
<TextView
android:id="@+id/data_text_view"
... />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// 创建数据列表
List<DataModel> dataList = new ArrayList<>();
dataList.add(new DataModel("Data 1"));
dataList.add(new DataModel("Data 2"));
// ...
// 创建适配器并设置给RecyclerView
mAdapter = new MyAdapter(dataList);
mRecyclerView.setAdapter(mAdapter);
}
}
这样,RecyclerView中的每个列表项就会显示一个序列号,并且根据数据列表动态更新序列号和数据内容。
推荐的腾讯云相关产品:无
领取专属 10元无门槛券
手把手带您无忧上云