RecyclerView架构如何处理嵌套适配器

时间:2016-06-18 18:45:55

标签: android

android RecyclerView如何处理嵌套视图,我有一个适配器json复杂但图像多次重复

"id": "c200",
            "name": "Ravi Tamada",
            "email": "ravi@gmail.com",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": [{
                "image": "image.png",
                "image": "image.png",
                "image": "image.png"
            }}
            }

如何展示图片

enter image description here

1 个答案:

答案 0 :(得分:0)

You have two options.

  1. you can use a LinearLayout inside your card and inflate a customLayout containing ImageView
  2. you can use a RecyclerView inside your card.

Explaining the option 2 -

You can use another RecyclerView inside the existing one.

The cardView -

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView  
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ViewAllLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical"
android:paddingBottom="8dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
.
.
.
.

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="4dp"
    android:paddingRight="4dp"
    android:paddingTop="4dp"/>
.
.
.
</LinearLayout>
</android.support.v7.widget.CardView>

The ViewHolder for the parent recyclerView will change to something like this.

    class MyViewHolder2 extends RecyclerView.ViewHolder {

    RecyclerView recyclerView;
    MyHorizontalAdapter horizontalAdapter;
......//rest of objects
.....

    public MyViewHolder2(View itemView) {
        super(itemView);
        recyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        horizontalAdapter = new MyHorizontalAdapter(context);
        recyclerView.setAdapter(horizontalAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        .....//rest of initialization codes
        .....
        .....
    }

    public void bind(JSONObject object) throws JSONException {
        horizontalAdapter.setHorizontalData(object.getJSONArray("phone"));
        ........//rest of bind data
        .......
        .......

    }

Donot forget the line

    recyclerView.setNestedScrollingEnabled(false);

It disallows the horizontal recyclerView to intercept vertical scroll.

In the HorizontalAdapter use it as u would a normal RecyclerView adapter. Since you are loading images, you can use libraries like Picasso or Glide in it.

The funtion-

public void setHorizontalData(JSONArray data){
....
notifyDataSetChanged();
}