我想在 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/