我有一个带全屏RecyclerView的活动来加载图片。用户可以左右滑动以查看下一个项目(通过LinearSnapHelper
实现此目的)在图像上,它具有浮动操作栏,其操作是下载当前可见的图像。
问题是当我点击FAB时,而不是下载当前图像,它下载下一个项目。因为onBindViewHolder
会提前执行下一个和上一个项目。当FAB是项目布局的一部分时不会出现问题,但在这种情况下,Fab是活动布局的一部分。
适配器 -
public class FullWallAdapter extends RecyclerView.Adapter<FullscreenViewHolder> {
private ArrayList<String> mWallKeys;
private OnFullSetupViewListener mOnFullSetupViewListener;
public FullWallAdapter(ArrayList<String> wallKeys, OnFullSetupViewListener listener) {
this.mWallKeys = wallKeys;
this.mOnFullSetupViewListener = listener;
}
@Override
public FullscreenViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.fullscreen_wallpaper_preview, parent, false);
return new FullscreenViewHolder(itemView);
}
@Override
public void onBindViewHolder(final FullscreenViewHolder holder, int position) {
ValueEventListener wallListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ImageModel image = dataSnapshot.getValue(ImageModel.class);
mOnFullSetupViewListener.onSetupView(holder, image, holder.getAdapterPosition(), dataSnapshot.getKey());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("WallAdapter", "Error occurred: " + databaseError.getMessage());
}
};
DatabaseReference ref = FireUtils.getWallpapersRef().child(mWallKeys.get(position));
ref.addValueEventListener(wallListener);
holder.mWallRef = ref;
holder.mWallListener = wallListener;
}
@Override
public int getItemCount() {
return mWallKeys.size();
}
@Override
public void onViewRecycled(FullscreenViewHolder holder) {
super.onViewRecycled(holder);
if (holder.mWallListener != null)
holder.mWallRef.removeEventListener(holder.mWallListener);
}
public interface OnFullSetupViewListener {
void onSetupView(FullscreenViewHolder holder, ImageModel image, int position, String wallKey);
}
}
活动 -
FullWallAdapter adapter = new FullWallAdapter(wallKeys, new FullWallAdapter.OnFullSetupViewListener() {
@Override
public void onSetupView(final FullscreenViewHolder holder, final ImageModel image,
int position, final String wallKey) {
holder.setImageView(image);
downloadFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
incrementDownload(wallKey, image);
String params;
params = wallpaper.getPhotoJson();
fetchSave(params);
}
});
}
});
答案 0 :(得分:2)
我只能想到解决方案如下。 每次用户滚动时触发onClickListener。
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentPosition = llm.findFirstVisibleItemPosition();
downloadFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
}
}