如何获取Recyclerview的特定项目的ViewHolder [英] How to get ViewHolder of specific Item of Recyclerview
问题描述
有没有办法仅基于给定位置获取recyclerview的特定项目的ViewHolder
?
Is there a way to get the ViewHolder
of specific Item of recyclerview base on given position only?
类似于getViewHolder(position);
.
public MyViewHolder getViewHolder(int position){
MyViewHolder holder = null;
/**
Find ViewHolder here...
If Found initialize the holder..
holder = ?
**/
return holder;
}
此函数在我的Adapter类中,我正在寻找一种获取项目ViewHolder
的方法,以便可以更改自定义项目eg. holder.setText("Hello World");
的某个视图的值,我有库存,我找不到解决方法,我尝试搜索,但没有一个能帮助我.
This function is in my Adapter class, I'm looking for a way to get the ViewHolder
of an Item so I can change the value of one of my view of my custom item eg. holder.setText("Hello World");
, I'm stock, I can't find a way to do that, I tried to search but none of them help me.
有人吗?
推荐答案
这不是ViewHolder的工作原理. ViewHolder只是您制作的版式的所有者. ViewHolder是可自动重用的,因此,如果您有100个项目,则android不会创建100个ViewHolders,而不会创建一些在屏幕上可见的ViewHolders.如果滚动RecyclerView,则不可见项的ViewHolder将被重新使用.您只需要更改在方法onBindViewHolder
That is not how ViewHolder works. ViewHolder is just a holder of layout that you made. ViewHolder is automatically re-use-able, so if you have 100 items, android will not create 100 ViewHolders, instead of just some ViewHolders that visible on the screen. If you scroll the RecyclerView, the ViewHolder of non-visible item will be re-used. You just need to change the data on the ViewHolder that passed automatically on method onBindViewHolder
这里是例子
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.textViewTitle.setText(data.get(position).title);
holder.textViewContent.setText(data.get(position).content);
Context context = holder.button.getContext();
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "you clicked the button!", Toast.LENGTH_SHORT).show();
}
});
}
为了更加清楚,您应该做的是更改适配器中的特定数据,例如,您可以像这样在适配器中创建一个方法
To make it more clear, what you should do is change the specific data from your adapter, for example you can create a method in your adapter like this
public void changeItem(int position, ItemModel newItemModel){
mItemModelList.remove(position);
mItemModelList.add(position, newItemModel);
}
然后调用适配器的notifyItemChanged(int position)
.
这篇关于如何获取Recyclerview的特定项目的ViewHolder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!