将视图模型传递到回收器视图适配器中会导致内存泄漏吗?

问题描述 投票:0回答:1

目前我正在尝试视图模型,想知道将视图模型传递给 recyclerview 适配器是否会导致内存泄漏?适配器中视图模型的唯一目的是提供要在活动中显示的图像的新 url

我不知道界面是否是更好的方法,或者是否有更好的方法从回收器视图接收 onclick 事件?

这是我的代码:

查看模型:

public class WallDetailViewModel extends AndroidViewModel {
private final String apiAddress = "*";
private BlindWall detailWall;
private MutableLiveData<String> mainImageUrl;

public WallDetailViewModel(@NonNull Application application) {
    super(application);
}

public LiveData<String> getMainImageUrl() {
    if(mainImageUrl == null) {
        mainImageUrl = new MutableLiveData<>();
        mainImageUrl.postValue(getImageUrl(0));
    }
    return mainImageUrl;
}

public void setWall(BlindWall wall) {
    detailWall = wall;
}

public String getImageUrl(int position) {
    String returnValue = null;
    if(position >= 0 && position < detailWall.getImagesUrls().size()) {
        returnValue = apiAddress + detailWall.getImagesUrls().get(position);
    }
    return returnValue;
}

public String getWallName() {
    return detailWall.getTitle();
}

public String getDutchDescription() {
    return detailWall.getDescriptionDutch();
}

public String getEnglishDescription() {
    return detailWall.getDescriptionEnglish();
}

public int getImageUrlSize() {
    return detailWall.getImagesUrls().size();
}

public void setMainImage(String url) {
    mainImageUrl.postValue(url);
}

}

适配器:

public class ImageSliderAdapter extends RecyclerView.Adapter<ImageSliderAdapter.ViewHolder2> {
private WallDetailViewModel viewModel;

public ImageSliderAdapter(WallDetailViewModel viewModel) {
    this.viewModel = viewModel;
}

public static class ViewHolder2 extends RecyclerView.ViewHolder {
    public ImageView WallFrontPaper;

    public ViewHolder2(View itemView) {
        super(itemView);
        WallFrontPaper = itemView.findViewById(R.id.ImageItem);
    }
}

@Override
public ViewHolder2 onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View v = inflater.inflate(R.layout.imageslider_item, parent, false);

    return new ViewHolder2(v);
}

@Override
public void onBindViewHolder(ViewHolder2 holder, int position) {
    Picasso.with(holder.itemView.getContext()).load(viewModel.getImageUrl(position)).fit().centerCrop().into(holder.WallFrontPaper);
    holder.WallFrontPaper.setOnClickListener(view -> viewModel.setMainImage(viewModel.getImageUrl(position)));
}

@Override
public int getItemCount() {
    return viewModel.getImageUrlSize();
}

}

谢谢你

android mvvm android-recyclerview viewmodel
1个回答
4
投票

从您发布的代码来看,我想说您应该没问题。但是,正如您所提到的,拥有一个界面可以帮助使事情变得更清晰,因为您可以将其传递给适配器,而无需暴露整个视图模型。

看着这一点

.setOnClickListener(view -> viewModel.setMainImage(viewModel.getImageUrl(position)));
让我想知道你是否不能仅仅通过让视图模型知道某个项目已被单击,因为你再次使用视图模型来根据位置确定要作为参数传递的图像网址.

因此,如果使用界面,您会看到类似

setOnClickListener(view -> itemClickListener.itemClicked(position)
的内容。您的视图模型将实现此接口。

© www.soinside.com 2019 - 2024. All rights reserved.