我想实现具有多种视图类型的RecyclerView。因此,我在适配器类中使用getItemViewType()
方法:
@Override
public int getItemViewType(int position) {
return mItems.get(position).getType();
}
现在,出现以下错误:
不兼容的类型。必需的int。找到了字符串。
我知道:这是因为getType()
方法返回的是String而不是int。
问题:如何返回整数?
答案 0 :(得分:2)
您可以简单地为您的类型或局部变量创建一个枚举,并返回如下内容:
companion object {
private const val MY_MESSAGE = 0
private const val OTHER_MESSAGE = 1
}
override fun getItemViewType(position: Int): Int {
val item = mMessages[position]
return if (item.isMine)
MY_MESSAGE
else
OTHER_MESSAGE
}
答案 1 :(得分:1)
您必须将String
转换为Integer
值。
public class CustomAdapter {
private static final int VIEW_TYPE_DEFAULT = 0;
private static final int VIEW_TYPE_1 = 1;
private static final int VIEW_TYPE_2 = 2;
private static final int VIEW_TYPE_3 = 3;
private static final int VIEW_TYPE_4 = 4;
@Override
public int getItemViewType(int position) {
String typeString = mItems.get(position).getType();
switch (typeString) {
case "STRING1":
return VIEW_TYPE_1;
case "STRING2":
return VIEW_TYPE_2;
case "STRING3":
return VIEW_TYPE_3;
....
default:
return VIEW_TYPE_DEFAULT;
}
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_1;
//bind viewtype 1
break;
case VIEW_TYPE_2;
//bind viewtype 2
break;
case VIEW_TYPE_3;
//bind viewtype 3
break;
....
default:
// Bind default view
}
}
}
答案 2 :(得分:1)
//Use Enums to separate the items type in the view.
enum class RecyclerViewDataType(val type: Int, val desc: String) {
TYPE_HEADER(1, "Header"),
TYPE_DATA(2, "Data"),
TYPE_FOOTER(3, "Footer")
}
// Model to Define the Data
data class DataWithHeader(
val viewType: RecyclerViewDataType,
val headerLayoutResId: Int = R.layout.header,
val data: Data = Data()
)
var items: List<DataWithHeader>
//viewType.type returns the required integer a/c to the item.
override fun getItemViewType(position: Int): Int {
return items[position].viewType.type
}
答案 3 :(得分:1)
要在recyclerview中处理视图类型,您的ArrayList应该具有某些唯一类型,或者必须具有getType()函数
public abstract class Vehicle {
protected int mType;
protected String mName;
abstract int getType();
abstract int getName();
public static class Types{
int MotorCar = 1;
int Bike = 2;
int Truck = 3;
}
}
public class Ferrari extends Vehicle {
public Ferrari{
this.mType = Vehicle.Types.MotorCar;
this.mName = "MotorCar";
}
@Override
public int getType(){
return mType;
}
@Override
public String getName(){
return mName;
}
}
public class Yamaha extends Vehicle{
public Yamaha{
this.mType = Vehicle.Types.Bike;
this.mName = "Bike";
}
@Override
public int getType(){
return mType;
}
@Override
public String getName(){
return mName;
}
}
这样,当调用getItemViewType时,它将根据对象类型返回您想要的类型。