如您所知,如果我们想在RecyclerView
中实现多种类型,我们应该提供多个CustomViewHolder
扩展RecyclerView.ViewHolder
。
对于exmpale,
class TextViewHolder extends RecyclerView.ViewHolder{
TextView textView;
}
class ImageViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
}
然后我们必须覆盖getItemViewType
。并在onCreateViewHolder
中构建TextViewHolder
或ImageViewHolder
。
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new ImageViewHolder(mLayoutInflater.inflate(R.layout.item_image, parent, false));
} else {
return new TextViewHolder(mLayoutInflater.inflate(R.layout.item_text, parent, false));
}
}
以上代码是正常的,但还有另一种方式。
我认为只有一个CustomViewHolder
就足够了。
class MultipleViewHolder extends RecyclerView.ViewHolder{
TextView textView;
ImageView imageView;
MultipleViewHolder(View itemView, int type){
if(type == 0){
textView = (TextView)itemView.findViewById(xx);
}else{
imageView = (ImageView)itemView.findViewById(xx);
}
}
}
您在开发工作中使用哪种方式?
答案 0 :(得分:27)
我个人喜欢Yigit Boyar this talk建议的方法(快进到31:07)。而不是从getItemViewType()
返回常量int ,而是直接返回布局ID,这也是一个int并保证是唯一的:
@Override
public int getItemViewType(int position) {
switch (position) {
case 0:
return R.layout.first;
case 1:
return R.layout.second;
default:
return R.layout.third;
}
}
这将允许您在onCreateViewHolder()
中执行以下操作:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(viewType, parent, false);
MyViewHolder holder = null;
switch (viewType) {
case R.layout.first:
holder = new FirstViewHolder(view);
break;
case R.layout.second:
holder = new SecondViewHolder(view);
break;
case R.layout.third:
holder = new ThirdViewHolder(view);
break;
}
return holder;
}
MyViewHolder
是抽象类:
public static abstract class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
// perform action specific to all viewholders, e.g.
// ButterKnife.bind(this, itemView);
}
abstract void bind(Item item);
}
FirstViewHolder
正在关注:
public static class FirstViewHolder extends MyViewHolder {
@BindView
TextView title;
public FirstViewHolder(View itemView) {
super(itemView);
}
@Override
void bind(Item item) {
title.setText(item.getTitle());
}
}
这会使onBindViewHolder()
成为一行:
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.bind(dataList.get(holder.getAdapterPosition()));
}
因此,您将每个ViewHolder
分开,其中bind(Item)
将负责执行仅针对该ViewHolder
的操作。
答案 1 :(得分:2)
我喜欢使用单一的责任类,因为逻辑没有混合。
使用第二个例子,您可以快速输入spaguetti代码,如果您想检查可空性,您将被迫声明"所有内容"可以为空。
答案 2 :(得分:1)
我使用两者,无论对当前任务更好。我确实尊重单一责任原则。每个ViewHolder都应该完成一项任务。
如果我对不同的项目类型有不同的视图持有者逻辑 - 我实现了不同的视图持有者。
如果可以将某些不同项类型的视图转换为相同类型并且不使用检查(例如,如果列表页眉和列表页脚是简单但不同的视图),则无法创建具有不同视图的相同视图持有者
这就是重点。不同的逻辑 - 不同的ViewHolders。相同的逻辑 - 相同的ViewHolders。
ImageView和TextView示例。 如果你的视图持有者有一些逻辑(例如,设置值),并且对于不同的视图类型它们是不同的 - 你不应该混合它们。
这是一个不好的例子:
class MultipleViewHolder extends RecyclerView.ViewHolder{
TextView textView;
ImageView imageView;
MultipleViewHolder(View itemView, int type){
super(itemView);
if(type == 0){
textView = (TextView)itemView.findViewById(xx);
}else{
imageView = (ImageView)itemView.findViewById(xx);
}
}
void setItem(Drawable image){
imageView.setImageDrawable(image);
}
void setItem(String text){
textView.setText(text);
}
}
如果您的ViewHolders没有任何逻辑,只是持有视图,对于简单的情况可能没问题。例如,如果以这种方式绑定视图:
@Override
public void onBindViewHolder(ItemViewHolderBase holder, int position) {
holder.setItem(mValues.get(position), position);
if (getItemViewType(position) == 0) {
holder.textView.setText((String)mItems.get(position));
} else {
int res = (int)mItems.get(position);
holder.imageView.setImageResource(res);
}
}
答案 3 :(得分:1)
这可能不是你期待的答案,但这是一个使用Epoxy的例子,这真的让你的生活更轻松:
首先定义模型:
@EpoxyModelClass(layout = R.layout.header_view_model)
public abstract class HeaderViewModel extends EpoxyModel<TextView> {
@EpoxyAttribute
String title;
@Override
public void bind(TextView view) {
super.bind(view);
view.setText(title);
}
}
@EpoxyModelClass(layout = R.layout.drink_view_model)
public abstract class DrinkViewModel extends EpoxyModel<View> {
@EpoxyAttribute
Drink drink;
@EpoxyAttribute
Presenter presenter;
@Override
public void bind(View view) {
super.bind(view);
final TextView title = view.findViewById(R.id.title);
final TextView description = view.findViewById(R.id.description);
title.setText(drink.getTitle());
description.setText(drink.getDescription());
view.setOnClickListener(v -> presenter.drinkClicked(drink));
}
@Override
public void unbind(View view) {
view.setOnClickListener(null);
super.unbind(view);
}
}
@EpoxyModelClass(layout = R.layout.food_view_model)
public abstract class FoodViewModel extends EpoxyModel<View> {
@EpoxyAttribute
Food food;
@EpoxyAttribute
Presenter presenter;
@Override
public void bind(View view) {
super.bind(view);
final TextView title = view.findViewById(R.id.title);
final TextView description = view.findViewById(R.id.description);
final TextView calories = view.findViewById(R.id.calories);
title.setText(food.getTitle());
description.setText(food.getDescription());
calories.setText(food.getCalories());
view.setOnClickListener(v -> presenter.foodClicked(food));
}
@Override
public void unbind(View view) {
view.setOnClickListener(null);
super.unbind(view);
}
}
然后定义Controller
:
public class DrinkAndFoodController extends Typed2EpoxyController<List<Drink>, List<Food>> {
@AutoModel
HeaderViewModel_ drinkTitle;
@AutoModel
HeaderViewModel_ foodTitle;
private final Presenter mPresenter;
public DrinkAndFoodController(Presenter presenter) {
mPresenter = presenter;
}
@Override
protected void buildModels(List<Drink> drinks, List<Food> foods) {
if (!drinks.isEmpty()) {
drinkTitle
.title("Drinks")
.addTo(this);
for (Drink drink : drinks) {
new DrinkViewModel_()
.id(drink.getId())
.drink(drink)
.presenter(mPresenter)
.addTo(this);
}
}
if (!foods.isEmpty()) {
foodTitle
.title("Foods")
.addTo(this);
for (Food food : foods) {
new FoodViewModel_()
.id(food.getId())
.food(food)
.presenter(mPresenter)
.addTo(this);
}
}
}
}
初始化您的Controller
:
DrinkAndFodController mController = new DrinkAndFoodController(mPresenter);
mController.setSpanCount(1);
final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
layoutManager.setSpanSizeLookup(mController.getSpanSizeLookup());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mController.getAdapter());
最后,您可以像这样轻松添加数据:
final List<Drink> drinks = mManager.getDrinks();
final List<Food> foods = mManager.getFoods();
mController.setData(drinks, foods);
您的列表如下:
Drinks
Drink 1
Drink 2
Drink 3
...
Foods
Food1
Food2
Food3
Food4
...
有关更多信息,您可以查看wiki。
答案 4 :(得分:0)
第二个是错误的,因为当ViewHolders被回收时会产生意外行为。我考虑过在绑定过程中更改可见性,但对于大量的视图来说,它的性能不够。 RecyclerView中的Recycler存储每种类型的ViewHolders,因此第一种方式更具性能。
答案 5 :(得分:0)
我有点使用第一个。
我使用一个伴随对象来声明我在实现中使用的静态字段。
这个项目是用kotlin编写的,但这是我实现适配器的方式:
/**
* Created by Geert Berkers.
*/
class CustomAdapter(
private val objects: List<Any>,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val FIRST_CELL = 0
const val SECOND_CELL = 1
const val THIRD_CELL = 2
const val OTHER_CELL = 3
const val FirstCellLayout = R.layout.first_cell
const val SecondCellLayout = R.layout.second_cell
const val ThirdCellLayout = R.layout.third_cell
const val OtherCellLayout = R.layout.other_cell
}
override fun getItemCount(): Int = 4
override fun getItemViewType(position: Int): Int = when (position) {
objects[0] -> FIRST_CELL
objects[1] -> SECOND_CELL
objects[2] -> THIRD_CELL
else -> OTHER_CELL
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
FIRST_CELL -> {
val view = inflateLayoutView(FirstCellLayout, parent)
return FirstCellViewHolder(view)
}
SECOND_CELL -> {
val view = inflateLayoutView(SecondCellLayout, parent)
return SecondCellViewHolder(view)
}
THIRD_CELL -> {
val view = inflateLayoutView(ThirdCellLayout, parent)
return ThirdCellViewHolder(view)
}
else -> {
val view = inflateLayoutView(OtherCellLayout, parent)
return OtherCellViewHolder(view)
}
}
}
fun inflateLayoutView(viewResourceId: Int, parent: ViewGroup?, attachToRoot: Boolean = false): View =
LayoutInflater.from(parent?.context).inflate(viewResourceId, parent, attachToRoot)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
val itemViewTpe = getItemViewType(position)
when (itemViewTpe) {
FIRST_CELL -> {
val firstCellViewHolder = holder as FirstCellViewHolder
firstCellViewHolder.bindObject(objects[position])
}
SECOND_CELL -> {
val secondCellViewHolder = holder as SecondCellViewHolder
secondCellViewHolder.bindObject(objects[position])
}
THIRD_CELL -> {
val thirdCellViewHolder = holder as ThirdCellViewHolder
thirdCellViewHolder.bindObject(objects[position])
}
OTHER_CELL -> {
// Do nothing. This only displays a view
}
}
}
}
以下是ViewHolder的一个示例:
class FirstCellViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindMedication(object: Object) = with(object) {
itemView.setOnClickListener {
openObject(object)
}
}
private fun openObject(object: Object) {
val context = App.instance
val intent = DisplayObjectActivity.intent(context, object)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
答案 6 :(得分:0)
您可以在此处使用动态方法调度。下面我分享我的想法。 //活动代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<Object> dataList = new ArrayList<>();
dataList.add("Apple");
dataList.add("Orange");
dataList.add("Cherry");
dataList.add("Papaya");
dataList.add("Grapes");
dataList.add(100);
dataList.add(200);
dataList.add(300);
dataList.add(400);
ViewAdapter viewAdapter = new ViewAdapter(dataList);
recyclerView.setAdapter(viewAdapter);
}
}
//适配器代码
public class ViewAdapter extends RecyclerView.Adapter<BaseViewHolder> {
private ArrayList<Object> dataList;
public ViewAdapter(ArrayList<Object> dataList) {
this.dataList = dataList;
}
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
BaseViewHolder baseViewHolder;
if(viewType == 0) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_one,parent,false);
baseViewHolder = new ViewHolderOne(view);
}else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_two,parent,false);
baseViewHolder = new ViewHolderSecond(view);
}
return baseViewHolder;
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
holder.bindData(dataList.get(position));
}
@Override
public int getItemViewType(int position) {
Object obj = dataList.get(position);
int type = 0;
if(obj instanceof Integer) {
type = 0;
}else if(obj instanceof String) {
type = 1;
}
return type;
}
@Override
public int getItemCount() {
return dataList != null ? dataList.size() : 0;
}
}
//基本视图持有人代码。
public abstract class BaseViewHolder<T> extends RecyclerView.ViewHolder {
public BaseViewHolder(View itemView) {
super(itemView);
}
public abstract void bindData(T data);
}
//查看Holder One源代码。
public class ViewHolderOne extends BaseViewHolder<Integer> {
private TextView txtView;
public ViewHolderOne(View itemView) {
super(itemView);
txtView = itemView.findViewById(R.id.txt_number);
}
@Override
public void bindData(Integer data) {
txtView.setText("Number:" + data);
}
}
//查看Holder Two
public class ViewHolderSecond extends BaseViewHolder<String> {
private TextView textView;
public ViewHolderSecond(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.txt_string);
}
@Override
public void bindData(String data) {
textView.setText("Text:" + data);
}
}
对于项目来源: enter link description here
答案 7 :(得分:0)
我强烈地使用这种方法: http://frogermcs.github.io/inject-everything-viewholder-and-dagger-2-example/ 简而言之:
onCreateViewHolder
委托给注入的工厂。onBind
,以便您可以使用onBindViewHolder
中的检索数据调用它。getItemViewType
选择工厂(instanceOf
或比较字段值)。为什么呢?
它将每个视图持有者与应用程序的其余部分完全分开。
如果您使用Google提供的autofactory
,则可以轻松注入每个视图所有者所需的依赖项。如果您需要通知某个事件的父级,只需创建新接口,在父视图(活动)中实现它并在dagger中公开它。 (专业提示:而不是从供应商处初始化工厂,只需指定每个必需项目的工厂取决于autofactory为您提供的工厂,而匕首将为您提供)。
我们将它用于+15个视图持有者,并且每个新添加的(getItemViewType
个检查)适配器只需增加~3行。
答案 8 :(得分:-1)
我在没有条件的情况下使用第二种方法,在列表中有超过100种项目。
public class SafeHolder extends RecyclerView.ViewHolder
{
public final ImageView m_ivImage;
public final ImageView m_ivRarity;
public final TextView m_tvItem;
public final TextView m_tvDesc;
public final TextView m_tvQuantity;
public SafeHolder(View itemView) {
super(itemView);
m_ivImage =(ImageView)itemView.findViewById(R.id.safeimage_id);
m_ivRarity =(ImageView)itemView.findViewById(R.id.saferarity_id);
m_tvItem = (TextView) itemView.findViewById(R.id.safeitem_id);
m_tvDesc = (TextView) itemView.findViewById(R.id.safedesc_id);
m_tvQuantity = (TextView) itemView.findViewById(R.id.safequantity_id);
}
}