Android studio 实现多个view list 在同一页面显示
时间: 2024-03-26 11:41:46 浏览: 161
要在 Android Studio 中实现多个 View List 在同一页中显示,你可以使用 RecyclerView 和多个 Adapter。下面是一个简单的示例:
1. 在 XML 布局文件中定义 RecyclerView 和多个 RecyclerView。
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
```
2. 在 Java 代码中,在 onCreate() 方法中初始化 RecyclerView 并设置 LinearLayoutManager。
```
RecyclerView recyclerView1 = findViewById(R.id.recycler_view_1);
RecyclerView recyclerView2 = findViewById(R.id.recycler_view_2);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(this);
recyclerView1.setLayoutManager(layoutManager1);
recyclerView2.setLayoutManager(layoutManager2);
```
3. 创建多个 Adapter 并将其设置为每个 RecyclerView 的 Adapter。
```
MyAdapter adapter1 = new MyAdapter(data1);
MyAdapter adapter2 = new MyAdapter(data2);
recyclerView1.setAdapter(adapter1);
recyclerView2.setAdapter(adapter2);
```
4. 在 Adapter 中实现自定义布局和数据的绑定。
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<MyData> mDataList;
public MyAdapter(List<MyData> dataList) {
mDataList = dataList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MyData data = mDataList.get(position);
holder.myTextView.setText(data.getText());
holder.myImageView.setImageResource(data.getImageId());
}
@Override
public int getItemCount() {
return mDataList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView myTextView;
public ImageView myImageView;
public MyViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.my_text_view);
myImageView = itemView.findViewById(R.id.my_image_view);
}
}
}
```
这样,你就可以在同一页中显示多个 View List 了。
阅读全文