android - 如何在 DialogFragment 中观察 ViewModel LiveData?

标签 android android-fragments android-dialogfragment

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

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

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

对话框 fragment :

@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 将位图从 fragment 发送到 dialogFragment。我在这里错过了什么?为什么我在dialogFragment中获取不到我在fragment中设置的位图图片?任何指示都会有所帮助。

谢谢

更新: 添加 View 模型代码,

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);
    }
}

最佳答案

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

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

将其添加到此处以供将来引用。

关于android - 如何在 DialogFragment 中观察 ViewModel LiveData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020636/

相关文章:

android - 如何通过 phonegap 应用程序在 facebook 上共享数据

android - 在 ViewPager 中回收 fragment

android - 运行时新的首选项支持库不正确的主题

android - 使用 FragmentPagerAdapter 在 android ViewPager 中滑动不工作

android - 从 fragment 显示对话框?

java - 来自 DialogFragment 的 Twitter 回调 URL

android - 与 ObservableField<> 的 2 向数据绑定(bind),set() 不起作用?

android - 无法以随机顺序恢复 Activity

Android:从 AlertDialog onClick 外部传递变量

java - 如何创建新的 "circle"datepicker android 对话框