如何在 DialogFragment 中观察 ViewModel LiveData?

How to observe ViewModel LiveData in a DialogFragment?

我想在片段和 dialogFragment 之间共享一个 ViewModel。在启动 DialogFragment 之前,我使用 setter 方法更新了 ViewModel liveData。当我尝试观察 DialogFragment 中的值时,该值为空。我尝试通过 bundle 的 parcelable 发送值,它成功了。

这就是我从片段中调用的方式,

myViewModel.setBitmap(myResult.getBitmap());
            BottomSheetFragment bottomSheetFragment = BottomSheetFragment.getNewInstance(args);
            bottomSheetFragment.setTargetFragment(this, EDIT_FROM_OVERLAY);
            bottomSheetFragment.setListener(this);
            bottomSheetFragment.show(fragmentManager, BottomSheetFragment.TAG);

对话片段:

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
        myViewModel.getBitMap().observe(this, bitmap ->
        {
            dialogBitmap = bitmap;
        });

        imageView = view.findViewById(R.id.overlay_image);
        imageView.setImageBitmap(dialogBitmap);
    }

我也尝试在 onCreateDialog 方法中初始化 ViewModel。结果还是一样。我想通过 ViewModel 将位图从片段发送到 dialogFragment。我在这里错过了什么?为什么我在dialogFragment中获取不到我在fragment中设置的位图图片?任何指示都会有所帮助。

谢谢

更新: 添加视图模型代码,

public class MyViewModel extends AndroidViewModel
{
    private final MutableLiveData<Bitmap> bitmap = new MutableLiveData<>();

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

    public LiveData<Bitmap> getBitmap()
    {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap)
    {
        bitmap.setValue(bitmap);
    }

    public void clear()
    {
        bitmap.setValue(null);
    }
}

这是因为你在创建dialogFragment之前设置了liveData值。

这样做 myViewModel.setBitmap(myResult.getBitmap());bottomSheetFragment.show(fragmentManager, BottomSheetFragment.TAG);

@Ali Rezaiyan 的建议让我意识到我没有在 fragment 上设置正确的值。 所以我在对话框片段中移动了设置位图。

bitmapViewModel.getBitmap().observe(this, bitmap ->
        {
            imageView.setImageBitmap(bitmap);
        });

添加到这里以备将来参考。

你做错了。使用您的方法,当您执行 imageView.setImageBitmap(dialogBitmap).

时,bitmap/dialogBitmap 的值将始终为 null

更好的方法是将 setImageBitmap 调用放在 LiveData 观察调用中。此外,记得始终检查 null。这是说明我的意思的代码片段:

// initialize your imageView
imageView = view.findViewById(R.id.overlay_image);

// observe your data
myViewModel.getBitMap().observe(this, bitmap ->
    {
        // check for null and set your imageBitmap accordingly
        if(bitmap != null) imageView.setImageBitmap(bitmap);
    });