带有多个适配器且viewtype无法正常工作的Recycler View

时间:2017-11-05 16:24:46

标签: java android android-layout android-recyclerview adapter

这是我要求的原型: enter image description here 我得到了什么结果 enter image description here

我在单个RecylerView中尝试使用多个viewtype,但我没有得到所需的结果。如果使用getItemViewType(),则无法获得需要编写的逻辑。请帮帮我

这是我想在RecylerView中实现的JSON数据

 {
  "rows": [{
    "sequence_id":1,
    "sequence_description":"animal description goes here",
    "sequence_image":"thumbnail.png",
    "sequence_title": "Animal",    
    "child_rows":[
      {
        "id": "1",
        "name":"Lion",
        "description" : "lion description goes here",
        "image": "Lion.png"

      },
      {
        "id": "2",
        "name":"Tiger",
        "description" : "Tiger description goes here",
        "image": "Tiger.png"
      },
      {
        "id": "3",
        "name":"Elephant",
        "description" : "Elephant description goes here",
        "image": "Elephant.png"
      }       
      ]
  },
{
    "sequence_id":2,
    "sequence_description":"animal description goes here",
    "sequence_image":"thumbnail.png",
    "sequence_title": "Birds",    
    "child_rows":[
      {
        "id": "1",
        "name":"Parrot",
        "description" : "Parrot description goes here",
        "image": "parrot.png"
      },
      {
        "id": "2",
        "name":"Pigeon",
        "description" : "Pigeon description goes here",
        "image": "Pigeon.png"
      },
      {
       "id": "3",
        "name":"Crow",
        "description" : "Crow description goes here",
        "image": "crow.png"
      }       
      ]
  }  
  ]
}

Activity.java

 mrecyclerview = (RecyclerView) findViewById(R.id.recyclerView);
        try {
            JSONObject jsonObj = new JSONObject(dataStr.getJsonString());


            JSONArray jsondata = jsonObj.getJSONArray("rows");


            for(int i = 0;i<jsondata.length();i++){
                JSONObject rowsdata = jsondata.getJSONObject(i);

                Integer sequence_id = rowsdata.getInt("sequence_id");
                String sequence_description = rowsdata.getString("sequence_description");
                String sequence_image = rowsdata.getString("sequence_image");
                String sequence_title = rowsdata.getString("sequence_title");



                List<ScreenOneInventory> minventorylist = new ArrayList<ScreenOneInventory>();
                ScreenOneRows soRows = new ScreenOneRows();
                JSONArray childres = rowsdata.getJSONArray("child_rows");
                for(int j =0;j<childres.length();j++){
                    JSONObject inventorydata = childres.getJSONObject(j);
                    Log.i("Fragment","I am here in loop j:"+j);
                    String id = inventorydata.getString("id");
                    String name = inventorydata.getString("name");
                    String description = inventorydata.getString("description");
                    String image = inventorydata.getString("image");


                    ScreenOneInventory soinventoryObj = new ScreenOneInventory();
                    soinventoryObj.setId(id);
                    soinventoryObj.setname(name);
                    soinventoryObj.setDescription(description);
                    soinventoryObj.setImage(image);

                    minventorylist.add(soinventoryObj);


                }


                soRows.setSequence_id(sequence_id);
                soRows.setSequence_Description(sequence_description);
                soRows.setSequence_image(sequence_image);
                soRows.setSop_title(sequence_title);

                soRows.setInventoryList(minventorylist);

                RowsData.add(soRows);



            }



        } catch (JSONException e) {
            e.printStackTrace();
        }


        mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        ScreenOneAdapter adapter = new ScreenOneAdapter(getActivity(),RowsData,mrecyclerview);
        mrecyclerview.setAdapter(adapter);
}

这是My Parent Rows适配器 ScreenOneAdapter.java

public class ScreenOneAdapter extends RecyclerView.Adapter<ScreenOneAdapter.BaseViewHolder> {

    private LayoutInflater mInflater;
    private List<ScreenOneRows> mRowsList;
    public static final int PARENT_VIEW = 0;
    public static final int CHILD_VIEW = 1;
    private RecyclerView recyclerView;
            private Context mcontext;
    public ScreenOneAdapter(Context context, List<ScreenOneRows> mRowsList, RecyclerView mrecyclerview) {
        this.mInflater = LayoutInflater.from(context);
        this.mRowsList = mRowsList;
        this.recyclerView = mrecyclerview;
        this.mcontext = context;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;


                view = mInflater.inflate(R.layout.list_item_rows,parent,false);
                RowsListHolder rowHolder = new RowsListHolder(view);
                return rowHolder;



    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        ScreenOneRows current = mRowsList.get(position);


        RowsListHolder rHolder =  (RowsListHolder) holder;
        rHolder.setData(current);
        List mInventoryList = current.getInventoryList();

       InventoryListAdapter iadapter = new InventoryListAdapter(mcontext,mInventoryList);
        recyclerView.setAdapter(iadapter);
    }

    @Override
    public int getItemCount() {
        return (null != mRowsList ? mRowsList.size() : 0);
    }




    public class BaseViewHolder extends RecyclerView.ViewHolder{

        public BaseViewHolder(View itemView) {
            super(itemView);
        }
    }

    public class RowsListHolder extends BaseViewHolder{
      private   ImageView icon;
      private TextView title;
      private TextView description;

        public RowsListHolder(View itemView) {
            super(itemView);

            icon = (ImageView) itemView.findViewById(R.id.img_icon);
            title = (TextView) itemView.findViewById(R.id.tvTitle);
            description = (TextView) itemView.findViewById(R.id.tvDescription);
        }
        public void setData(ScreenOneRows current){
            this.title.setText(current.getSequence_title());
            this.description.setText(current.getSequence_description());
        }


    }


}

这是我的子行适配器 InventoryListAdapter.java

public class InventoryListAdapter extends RecyclerView.Adapter<InventoryListAdapter.InventoryListHolder> {

    private List<ScreenOneInventory> mInventoryList;
    private LayoutInflater mInflater;
    public InventoryListAdapter(Context context, List<ScreenOneInventory> mInventoryList) {
        this.mInventoryList = mInventoryList;
        this.mInflater = LayoutInflater.from(context);
    }

    @Override
    public InventoryListAdapter.InventoryListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View rootView;
        rootView = mInflater.inflate(R.layout.list_item_inventory,parent,false);
        InventoryListHolder invHolder = new InventoryListHolder(rootView);
        return invHolder;
    }

    @Override
    public void onBindViewHolder(InventoryListAdapter.InventoryListHolder holder, int position) {
       ScreenOneInventory currentInv = mInventoryList.get(position);
        InventoryListHolder invenHolder = (InventoryListHolder) holder;
        invenHolder.setData(currentInv);
    }

    @Override
    public int getItemCount() {
        return (null != mInventoryList ? mInventoryList.size() : 0);
    }

    public class InventoryListHolder extends RecyclerView.ViewHolder {
      private ImageView imgicon;
     private TextView title;
     private TextView description;
        public InventoryListHolder(View itemView) {
            super(itemView);
            imgicon = (ImageView) itemView.findViewById(R.id.img_inv_icon);
            title = (TextView) itemView.findViewById(R.id.titletxt);
            description = (TextView) itemView.findViewById(R.id.descriptiontxt);
        }

        public void setData(ScreenOneInventory data) {
            this.title.setText(data.getName());
            this.status.setText(data.getDescription());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

无需创建两个不同的适配器您可以在Row和子项的情况下使用两个不同的项目布局。

您需要使用额外信息创建一个公共列表视图,例如此值是行值或子值。 如果行值为true,则膨胀item_row.xml 如果行值为false,则膨胀item_child.xml

我创建了示例应用程序您可以复制粘贴并检查

**主要活动**

public class MainActivity extends AppCompatActivity {
List<ScreenOneInventory> minventorylist = new ArrayList<ScreenOneInventory>();
List<ScreenOneRows> screenOneRowses = new ArrayList<>();
ArrayList<ItemInterface> finalList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String dataStr = "{\n" +
            "  \"rows\": [{\n" +
            "    \"sequence_id\":1,\n" +
            "    \"sequence_description\":\"animal description goes here\",\n" +
            "    \"sequence_image\":\"thumbnail.png\",\n" +
            "    \"sequence_title\": \"Animal\",    \n" +
            "    \"child_rows\":[\n" +
            "      {\n" +
            "        \"id\": \"1\",\n" +
            "        \"name\":\"Lion\",\n" +
            "        \"description\" : \"lion description goes here\",\n" +
            "        \"image\": \"Lion.png\"\n" +
            "\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"2\",\n" +
            "        \"name\":\"Tiger\",\n" +
            "        \"description\" : \"Tiger description goes here\",\n" +
            "        \"image\": \"Tiger.png\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"3\",\n" +
            "        \"name\":\"Elephant\",\n" +
            "        \"description\" : \"Elephant description goes here\",\n" +
            "        \"image\": \"Elephant.png\"\n" +
            "      }       \n" +
            "      ]\n" +
            "  },\n" +
            "{\n" +
            "    \"sequence_id\":2,\n" +
            "    \"sequence_description\":\"animal description goes here\",\n" +
            "    \"sequence_image\":\"thumbnail.png\",\n" +
            "    \"sequence_title\": \"Birds\",    \n" +
            "    \"child_rows\":[\n" +
            "      {\n" +
            "        \"id\": \"1\",\n" +
            "        \"name\":\"Parrot\",\n" +
            "        \"description\" : \"Parrot description goes here\",\n" +
            "        \"image\": \"parrot.png\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"2\",\n" +
            "        \"name\":\"Pigeon\",\n" +
            "        \"description\" : \"Pigeon description goes here\",\n" +
            "        \"image\": \"Pigeon.png\"\n" +
            "      },\n" +
            "      {\n" +
            "       \"id\": \"3\",\n" +
            "        \"name\":\"Crow\",\n" +
            "        \"description\" : \"Crow description goes here\",\n" +
            "        \"image\": \"crow.png\"\n" +
            "      }       \n" +
            "      ]\n" +
            "  }  \n" +
            "  ]\n" +
            "}";


    try {
        JSONObject jsonObj = new JSONObject(dataStr);


        JSONArray jsondata = jsonObj.getJSONArray("rows");


        for (int i = 0; i < jsondata.length(); i++) {
            JSONObject rowsdata = jsondata.getJSONObject(i);

            String sequence_id = rowsdata.getString("sequence_id");
            String sequence_description = rowsdata.getString("sequence_description");
            String sequence_image = rowsdata.getString("sequence_image");
            String sequence_title = rowsdata.getString("sequence_title");

            ScreenOneRows soRows = new ScreenOneRows();
            soRows.setSequence_id(sequence_id);
            soRows.setSequence_description(sequence_description);
            soRows.setSequence_image(sequence_image);
            soRows.setSequence_title(sequence_title);
            finalList.add(soRows);

            JSONArray childres = rowsdata.getJSONArray("child_rows");
            for (int j = 0; j < childres.length(); j++) {
                JSONObject inventorydata = childres.getJSONObject(j);
                Log.i("Fragment", "I am here in loop j:" + j);
                String id = inventorydata.getString("id");
                String name = inventorydata.getString("name");
                String description = inventorydata.getString("description");
                String image = inventorydata.getString("image");

                ScreenOneInventory soinventoryObj = new ScreenOneInventory();
                soinventoryObj.setId(id);
                soinventoryObj.setName(name);
                soinventoryObj.setDescription(description);
                soinventoryObj.setImage(image);
                finalList.add(soinventoryObj);

            }

        }

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        MyCustomAdapter myCustomAdapter = new MyCustomAdapter(finalList, this);
        recyclerView.setAdapter(myCustomAdapter);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

实体类

<强> ScreenOneInventory

class ScreenOneInventory implements ItemInterface {
String id;
String name;
String description;
String image;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

@Override
public boolean isRow() {
    return false;
}
}

<强> ScreenOneRows.java

class ScreenOneRows implements ItemInterface{
String sequence_id;
String sequence_description;
String sequence_image;
String sequence_title;

public String getSequence_id() {
    return sequence_id;
}

public void setSequence_id(String sequence_id) {
    this.sequence_id = sequence_id;
}

public String getSequence_description() {
    return sequence_description;
}

public void setSequence_description(String sequence_description) {
    this.sequence_description = sequence_description;
}

public String getSequence_image() {
    return sequence_image;
}

public void setSequence_image(String sequence_image) {
    this.sequence_image = sequence_image;
}

public String getSequence_title() {
    return sequence_title;
}

public void setSequence_title(String sequence_title) {
    this.sequence_title = sequence_title;
}

@Override
public boolean isRow() {
    return true;
}
}

Recycler view Adapter ** ** MyCustomAdapter.java

public class MyCustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public static final int ROW_VIEW = 0;
public static final int CHILD_VIEW = 1;

ArrayList<ItemInterface> finalList;
WeakReference<Context> mContextWeakReference;

public MyCustomAdapter(ArrayList<ItemInterface> finalList, Context context) {
    this.finalList = finalList;
    this.mContextWeakReference = new WeakReference<Context>(context);
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    Context context = mContextWeakReference.get();
    if (viewType == ROW_VIEW) {
        return new SectionViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false));
    }
    return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_child, parent, false), context);
}

@Override
public int getItemViewType(int position) {
    if (finalList.get(position).isRow()) {
        return ROW_VIEW;
    } else {
        return CHILD_VIEW;
    }
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    Context context = mContextWeakReference.get();

    if (context == null) {
        return;
    }

    if (ROW_VIEW == getItemViewType(position)) {

        SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
        ScreenOneRows screenOneRows = (ScreenOneRows) finalList.get(position);
        sectionViewHolder.textView.setText(screenOneRows.getSequence_title());
        sectionViewHolder.textView2.setText(screenOneRows.getSequence_description());
        return;
    }

    MyViewHolder myViewHolder = (MyViewHolder) holder;
    ScreenOneInventory childInventory = (ScreenOneInventory) finalList.get(position);
    myViewHolder.textView.setText(childInventory.getName());
    myViewHolder.textView2.setText(childInventory.getDescription());

}


@Override
public int getItemCount() {
    //return mUsersAndSectionList.size();
    return finalList.size();
}

//holder
public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView textView, textView2;
    ImageView image;

    public MyViewHolder(View itemView, final Context context) {

        super(itemView);
        textView = itemView.findViewById(R.id.textView);
        textView2 = itemView.findViewById(R.id.textView2);
        image = itemView.findViewById(R.id.image);
    }
}

public class SectionViewHolder extends RecyclerView.ViewHolder {
    TextView textView, textView2;
    ImageView image;

    public SectionViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.textView);
        textView2 = itemView.findViewById(R.id.textView2);
        image = itemView.findViewById(R.id.image);
    }


 }

<强> ItemInterface.java 此类用于制作泛型类型的arraylist,它可以使用一个适配器进行输入

public interface ItemInterface{
    boolean isRow();

}

<强> activity_main.xml中

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.my.stackoverflowrecyclerview.MainActivity"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg"
         />
</RelativeLayout>

<强> item_row.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_marginStart="50dp"
    android:background="#FFF"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:background="@mipmap/ic_launcher_round"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/image"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="12dp"
        android:layout_toEndOf="@+id/image"
        android:text="TextView" />

</RelativeLayout>

<强> item_child.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_marginStart="50dp"
    android:background="#FFF"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:background="@mipmap/ic_launcher_round"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/image"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="12dp"
        android:layout_toEndOf="@+id/image"
        android:text="TextView" />

</RelativeLayout>

这里是输出enter image description here