Несколько заголовков в recycleview не работают - почему так? - PullRequest
0 голосов
/ 17 июня 2019

Я хочу создать recycleview с несколькими заголовками, первый заголовок работает отлично, но остальные заголовки работают не так, как ожидалось. Это мой первый раз с заголовками recycleview. А также я хотел бы знать, является ли это правильным способом сделать это.

Вот мой адаптер.

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = RecyclerViewAdapter.class.getSimpleName();

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    private List<ItemObject> itemObjects;
    private Context context;


    public RecyclerViewAdapter( Context context , List<ItemObject> itemObjects) {
        this.context = context;
        this.itemObjects = itemObjects;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_HEADER) {
            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout, parent, false);
            return new HeaderViewHolder(layoutView);
        } else if (viewType == TYPE_ITEM) {
            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
            return new ItemViewHolder(layoutView , context);
        }
        throw new RuntimeException("No match for " + viewType + ".");
    }
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ItemObject mObject = itemObjects.get(position);
        if(holder instanceof HeaderViewHolder){
            ((HeaderViewHolder) holder).headerTitle.setText(mObject.getContents());
        }else if(holder instanceof ItemViewHolder){
            ((ItemViewHolder) holder).itemContent.setText(mObject.getContents());
        }
    }
    private ItemObject getItem(int position) {
        return itemObjects.get(position);
    }
    @Override
    public int getItemCount() {
        return itemObjects.size();
    }
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;
        return TYPE_ITEM;
    }
    private boolean isPositionHeader(int position) {
        return position == 0;
    }
}

и вот мой метод в основной деятельности.

recyclerView = findViewById(R.id.recyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this , getDataSource());
    recyclerView.setAdapter(adapter);
   private List <ItemObject> getDataSource(){
  List<ItemObject> list1 = new ArrayList <ItemObject>();

        list1.add(new ItemObject("First Header",true));
        list1.add(new ItemObject("This is the item content in the first position"));
        list1.add(new ItemObject("This is the item content in the second position"));


        List <ItemObject> list2 = new ArrayList <ItemObject>();
        list2.add(new ItemObject("Second Header",true));
        list2.add(new ItemObject("This is the item content in the first position"));
        list2.add(new ItemObject("This is the item content in the second position"));


        List <ItemObject> list3 = new ArrayList <ItemObject>();
        list3.add(new ItemObject("Third Header",true));
        list3.add(new ItemObject("This is the item content in the first position"));
        list3.add(new ItemObject("This is the item content in the second position"));

        List <ItemObject> finalList = new ArrayList <ItemObject>(list1);
        finalList.addAll(list1);
        finalList.addAll(list2);
        finalList.addAll(list3);

        return finalList;
[![I get first header 2 times][1]][1]
}

и вот мой класс объекта предмета.

public class ItemObject {
    private String contents;
    boolean isHeader ;


    public ItemObject(String contents, boolean isHeader) {
        this.contents = contents;
        this.isHeader = isHeader;
    }

    public ItemObject(String contents) {

        this.contents = contents;
    }

    public String getContents() {
        return contents;
    }

    public boolean isHeader() {
        return isHeader;
    }
}

Я получаю первый заголовок 2 раза, как это https://imgur.com/a/2YZ8DxM

Ответы [ 2 ]

0 голосов
/ 17 июня 2019

Заменить List <ItemObject> finalList = new ArrayList <ItemObject>(list1); finalList.addAll(list1); finalList.addAll(list2); finalList.addAll(list3);

С List <ItemObject> finalList = new ArrayList <ItemObject>(); finalList.addAll(list1); finalList.addAll(list2); finalList.addAll(list3)

вы добавляете первый заголовок два раза здесь

List <ItemObject> finalList = new ArrayList <ItemObject>(list1);
0 голосов
/ 17 июня 2019

List.addAll() просто объединяет элементы List, переданные в качестве параметра finalList. то есть вы получите List с 9 предметами. Вот почему ваше условие position == 0 работает только для вашего первого заголовка.

Одним из возможных (простых) решений будет изменение ItemObject, чтобы иметь флаг, указывающий, что данный элемент является заголовком (обратите внимание, что это второй параметр конструктора, true, являющийся заголовком, false в противном случае).

private List <ItemObject> getDataSource(){
    List<ItemObject> list1 = new ArrayList <ItemObject>();

    list1.add(new ItemObject("First Header", true));
    list1.add(new ItemObject("This is the item content in the first position", false));
    list1.add(new ItemObject("This is the item content in the second position", false));

    List <ItemObject> list2 = new ArrayList <ItemObject>();
    list2.add(new ItemObject("Second Header", true));
    list2.add(new ItemObject("This is the item content in the first position", false));
    list2.add(new ItemObject("This is the item content in the second position", false));

    List <ItemObject> list3 = new ArrayList <ItemObject>();
    list3.add(new ItemObject("Third Header", true));
    list3.add(new ItemObject("This is the item content in the first position", false));
    list3.add(new ItemObject("This is the item content in the second position", false));

    List <ItemObject> finalList = new ArrayList <ItemObject>(list1);
    finalList.addAll(list1);
    finalList.addAll(list2);
    finalList.addAll(list3);

    return finalList;
}

И тогда ваше состояние в адаптере будет примерно таким:

private boolean isPositionHeader(int position) {
    ItemObject mObject = itemObjects.get(position);
    return mObject.isHeader();
}
...