Я пытаюсь создать ящик для навигации с заголовками. У меня все работает с одним исключением. Сначала я дам краткую информацию о структуре, а затем сформулирую точный вопрос. структура выглядит следующим образом:RecyclerView не переключается между видами
У меня есть 2 макета файлов, один для заголовков ящика смотри называется header_row.xml. Он содержит два виджета, текстовое изображение и изображение. Ориентация вертикальная, поэтому в представлении viewtem будет отображаться изображение в текстовом режиме. Текстовым видом в этом макете является текст заголовка, а изображение - горизонтальная линия, которая находится под этим заголовком как простой разделитель.
Вторая компоновка - элементы, доступные для вызова. Он также содержит два виджета, один текстовый просмотр и одно изображение. textview - это элемент, который можно щелкнуть. И изображение - это значок этого элемента. Этот макет горизонтальный, поэтому значок находится слева от элемента. Этот макет называется data_row.xml.
Целью этих двух файлов макета является (попробуйте представить это), чтобы иметь просмотрщик с заголовками.
кодМой Ресайклер адаптер выглядит следующим образом:
package com.android.yousef.tm;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Yousef on 3/3/2015.
*/
public class MyRecyclerAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
String[] texts; //An array of the text elements that contains both header
//text and items text
int[] imgs; // An array of the image elements that contains both headers
//dividers and items icons.
// NOTE THAT, THE DATA IN THE ABOVE ARRAYS ARE ARRANGE IN ORDER SO THAT
//POSITIONS 0, 3, AND 5 WILL
// CONTAIN HEADER'S TEXT AND DIVIDER'S IMAGE RESOURCES
private ClickListner clickListner; // Ignore this
//My constructor as bellow getting data from the NavigationDrawer.java class
public MyRecyclerAdapter(String[] texts, int[] imgs) {
this.texts = texts;
this.imgs = imgs;
}
// Ignore the listner
public void setClickListner(ClickListner clickListner) {
this.clickListner = clickListner;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// positions 0,3,and 5 are my headers positions
if(i == 0 || i == 3 || i ==5)
{
// if the current position is a header's position then return a
//header_row item
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.header_row, viewGroup, false);
return new VHHeader(view);
}
else {
// if the current position is not a header's position then return an
//item_row item
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.data_row, viewGroup, false);
return new VHItem(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
// if the current position is a header's position then set header's
//value: text and divider
if(viewHolder instanceof VHHeader)
{
((VHHeader) viewHolder).header.setText(texts[i]);
((VHHeader) viewHolder).divider.setImageResource(imgs[i]);
}
// if the current position is not a header's position then set item's
//value: text and icon
else if(viewHolder instanceof VHItem)
{
((VHItem) viewHolder).title.setText(texts[i]);
((VHItem) viewHolder).icon.setImageResource(imgs[i]);
}
}
@Override
public int getItemCount() {
//total rows in my recycler view including header and clickable items.
return 8;
}
//Ignore the interface
public interface ClickListner {
public void itemClicked(View v, int position);
}
// My Item's ViewHolder class.
class VHItem extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public VHItem(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.list_txt_data);
icon = (ImageView) itemView.findViewById(R.id.list_img_data);
}
}
// My Header's ViewHolder class
class VHHeader extends RecyclerView.ViewHolder {
TextView header;
ImageView divider;
public VHHeader(View itemView) {
super(itemView);
header = (TextView) itemView.findViewById(R.id.list_txt_header);
divider = (ImageView) itemView.findViewById(R.id.list_img_header);
}
}
}
Проблема в том, что вид переработчик всегда занимает первое расположение строк (в моем случае header_row.xml) и использует его для всех строки относительно их положения и, следовательно, типы как заголовки (пользователи header_row.xml) или элементы (пользователи data_row.xml).
Любая помощь пожалуйста? Спасибо.
Возможно, instanceof не работает должным образом? В качестве альтернативы попробуйте установить теги для зрителей на onCreateViewHolder и использовать их в onBindViewHolder. – squeeish
Я попытался использовать параметр «i», положение этого вида, и он все еще не работал. –