【发布时间】:2019-11-24 17:49:32
【问题描述】:
我想在片段和对话框片段之间共享一个 ViewModel。在启动 DialogFragment 之前,我使用 setter 方法更新 ViewModel liveData。当我尝试观察 DialogFragment 中的值时,该值为空。我尝试通过捆绑包的 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);
}
}
【问题讨论】:
标签: android android-fragments android-dialogfragment