RecyclerView举个使用例子
时间: 2023-11-16 12:54:33 浏览: 145
RecyclerViewTest_recyclerview_android开发_nan_android_
好的,RecyclerView是Android中常用的一个控件,用于展示大量数据列表。使用RecyclerView需要以下步骤:
1. 在布局文件中添加RecyclerView控件
2. 创建一个Adapter类,继承自RecyclerView.Adapter,并实现其中的方法
3. 创建一个ViewHolder类,继承自RecyclerView.ViewHolder,并实现其中的方法
4. 在Activity或Fragment中初始化RecyclerView,并设置Adapter和LayoutManager
下面是一个简单的使用例子:
1. 在布局文件中添加RecyclerView控件
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 创建一个Adapter类
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.mTextView.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
}
}
}
```
3. 创建一个ViewHolder类
```
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
}
}
```
4. 在Activity或Fragment中初始化RecyclerView,并设置Adapter和LayoutManager
```
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);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add("Item " + i);
}
mAdapter = new MyAdapter(data);
mRecyclerView.setAdapter(mAdapter);
}
}
```
阅读全文