如何观察对话框片段中的ViewModel livedata?

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

我想在片段和对话框片段之间共享视图模型。在启动DialogFragment之前,我使用setter方法更新了viewmodel livedata。当我尝试观察DialogFragment中的值时,该值为null。我尝试通过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。结果还是一样。我想通过视图模型从片段发送一个位图到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
2个回答
0
投票

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

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


0
投票

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

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

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

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