java 如何使用viewModel发送AlertDialog片段的结果?

1sbrub3j  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(156)

我有一个自定义对话框片段,它使用Intent与其父对话框进行通信。(我从某个地方复制了它)。它使用旧的框架进行通信,它的一些方法,如onActivityResultgetTargetFragment()现在已被弃用。
我知道人们可以用新的方法替换这些过时的方法,例如How to replace setTargetFragment() now that it is deprecated,但是为了得到一个是或否的结果而走了这么长的路?!
有简单的方法吗?我尝试使用ViewModel,但不起作用!
我的视图模型尝试:AlertDialogViewModel.java

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class AlertDialogViewModel extends ViewModel {

    private final MutableLiveData<Boolean> mAlertDialogResult = new MutableLiveData();
    public LiveData<Boolean> getAlertDialogResult() {
        return mAlertDialogResult;
    }
    public void setAlertDialogResult(boolean mResult) {
        mAlertDialogResult.setValue(mResult);
    }

}

在网站内部MyAlertDialog.java:

public class MyAlertDialog extends DialogFragment {

    AlertDialogViewModel mViewModel;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        return new MaterialAlertDialogBuilder(requireContext())
                .setTitle(Title)
                .setMessage(MESSAGE)
                .setPositiveButton("YES", (d, b) -> onResult(true))
                .setNegativeButton("NO", (d, b) -> onResult(false))
                .create();
    }

    private void onResult(boolean result) {
       mViewModel.setAlertDialogResult(result);
    }
    private static void showResult(Framgment fragment) {
       dialog.show(fragment.getParentFragmentManager(), null);
    }
}

但当我想把它烤成:

MyAlertDialog.showResult(this)
AlertDialogViewModel model = new ViewModelProvider(this).get(AlertDialogViewModel.class);
        model.getAlertDialogResult().observe(this, result-> {
            Toast(this, ""+result,Toast.LENGTH_SHORT).show();
        });
gr8qqesn

gr8qqesn1#

你永远不会初始化你的对话框片段视图模型。你需要获得与宿主Activity或父片段中使用的示例相同的示例。

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Assumes requireContext() returns the Activity this dialog is shown in
    mViewModel = new ViewModelProvider(requireContext()).get(AlertDialogViewModel.class)

    return new MaterialAlertDialogBuilder(requireContext())
            .setTitle(Title)
            .setMessage(MESSAGE)
            .setPositiveButton("YES", (d, b) -> onResult(true))
            .setNegativeButton("NO", (d, b) -> onResult(false))
            .create();
}

然后确保在Fragment中获得相同的示例:

AlertDialogViewModel model = new ViewModelProvider(requireContenxt()).get(AlertDialogViewModel.class);
model.getAlertDialogResult().observe(this, result-> {
    Toast(this, ""+result,Toast.LENGTH_SHORT).show();
});

最后,什么是dialog,为什么它是静态的?

private static void showResult(Framgment fragment) {
   dialog.show(fragment.getParentFragmentManager(), null);
}

相关问题