如何在DialogFragment中观察ViewModel LiveData?

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

我想在一个片段和一个dialogFragment之间共享一个ViewModel。在启动DialogFragment之前,我使用setter方法更新了ViewModel liveData。当我尝试观察DialogFragment中的值时,该值为null。我尝试通过捆绑包的包裹发送该值,并且该方法有效。

这是我从片段中呼叫的方式,

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中获取在片段中设置的位图图像?任何指针都会有所帮助。

谢谢

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

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);
    }
}
android android-fragments android-dialogfragment
3个回答
0
投票

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

执行此操作myViewModel.setBitmap(myResult.getBitmap());bottomSheetFragment.show(fragmentManager, BottomSheetFragment.TAG);


0
投票

@@ Ali Rezaiyan的建议使我意识到,我并没有马上设定价值。所以我将设置位图移入对话框片段中的观察中。

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

在此处添加以供将来参考。


0
投票

您做错了这件事。使用您的方法,执行bitmapdialogBitmap / imageView.setImageBitmap(dialogBitmap)的值始终为null。

一种更好的方法是将setImageBitmap调用放在LiveData观察调用中。另外,记住始终检查是否为空。这是一个代码片段,它说明了我的意思:

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

我希望这会有所帮助。编码愉快!

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