我有一个带有2个ViewTypes的recyclerView:图像和1个按钮。当我点击该按钮时,我每次都可以再添加一个图像。我希望当我有5张图像时,按钮会消失,而不使用setView
(Gone)。这是我的适配器,我正在尝试删除onBindViewHolder
中的按钮:
public class SelectPhotoAdapter extends
RecyclerView.Adapter<SelectPhotoHolder> {// Recyclerview will extend to
// recyclerview adapter
private ArrayList<Data_Model> arrayList;
private Context context;
private boolean hasLoadButton = true;
private final int IMAGES = 0;
private final int LOAD_MORE = 1;
public SelectPhotoAdapter (Context context,
ArrayList<Data_Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
public boolean itHasLoadButton() {
return hasLoadButton;
}
public void setHasLoadButton(boolean hasLoadButton) {
this.hasLoadButton = hasLoadButton;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (hasLoadButton) {
return arrayList==null? 1 :arrayList.size() + 1;
} else {
return arrayList==null? 0 :arrayList.size();
}
}
@Override
public int getItemViewType(int position) {
if (position < getItemCount()-1) {
return IMAGES;
} else {
return LOAD_MORE;
}
}
@Override
public void onBindViewHolder(SelectPhotoHolder holder, int position) {
SelectPhotoHolder mainHolder = holder;// holder
if(position >= getItemCount() -1) {
mainHolder.addPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
arrayList.add(new Data_Model(SelectPhotoDialogFragment.IMAGES[0]));
SelectPhotoDialogFragment.adapter.notifyItemInserted(arrayList.size());
SelectPhotoDialogFragment.mRecyclerView.scrollToPosition(arrayList.size());
Log.d("askj","Sizee: "+arrayList.size());
if(arrayList.size()>5&&itHasLoadButton()){
setHasLoadButton(false);
SelectPhotoDialogFragment.adapter.notifyItemRemoved(arrayList.size() + 1);
SelectPhotoDialogFragment.adapter.notifyItemRangeChanged(arrayList.size() + 1, getItemCount());
Log.e("askj", "calledLoad");
}
}
});
} else {
final Data_Model model = arrayList.get(position);
Bitmap image = BitmapFactory.decodeResource(context.getResources(),
model.getImagePath());// This will convert drawbale image into
mainHolder.imageview.setImageBitmap(image);
}
}
@Override
public SelectPhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == IMAGES) {
return new SelectPhotoHolder((LayoutInflater.from(parent.getContext()).inflate(R.layout.selectphotolist, parent, false)),IMAGES);
} else if (viewType == LOAD_MORE) {
return new SelectPhotoHolder((LayoutInflater.from(parent.getContext()).inflate(R.layout.addphoto, parent, false)),LOAD_MORE);
} else {
return null;
}
}
}
调用该方法(我可以在控制台'calledLoad'中看到),但按钮仍在那里。我认为通过调用setHasLoadButton
(false)按钮将会消失,但它不会发生。
如果我需要添加更多代码,请告诉我。
答案 0 :(得分:1)
您可以将getItemViewType
中的条件从position < getItemCount()-1
更改为arrayList!=null && position < arrayList.size()
。
最好还将OnClickListener
界面的管理直接转移到ViewHolder
。