Android Fragments 如何使用片段的ComposeView中的视图侦听DialogFragment的回调

n53p2ov0  于 2023-06-06  发布在  Android
关注(0)|答案(1)|浏览(222)

在Fragment中的ComposeView中,无法使用Views侦听来自DialogFragment的回调
我尝试在一个大多数屏幕使用视图的项目中使用撰写。在一个片段中,我创建了一个合成视图,并显示了一个对话框片段

class MyFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return ComposeView(requireContext()).apply {
            setContent {
                MyScreen()
            }

        }
    }

    @Composable
    fun MyScreen() {
         LoginAlertDialog(LocalContext.current as Activity).show(){
            EventBus.getDefault().sendEvent(MyEvent())
       }
}

我的LoginAlertDialog只是一个带有视图的片段

class LoginAlertDialog(activity: Activity) : AlertDialog.Builder(activity) {

    private lateinit var binding: CustomAlertBinding

    fun show(isMain: Boolean, onDismiss: () -> Unit){
        val builder = AlertDialog.Builder(activity, R.style.CustomAlertDialog)
            .create()
        val inflater = (activity).layoutInflater
        binding = CustomAlertBinding.inflate(inflater)
        builder.setView(binding.root)
        builder.setCanceledOnTouchOutside(false)
        builder.show()

        binding.cancel.setOnClickListener {
             onDismiss()
        }
    }
}

但是onDismiss()在我单击取消时不会被触发。我做错了什么,如何在Compose中收听onDismiss()

mlmc2os5

mlmc2os51#

问题如下:你成功地执行了onDismiss,它通过事件总线发送了那个事件,但是你没有关闭实际的对话框。
要做到这一点,只需将builder.dismiss()行添加到cancel按钮上的click listener中,因此它就像下面这样:

class LoginAlertDialog(activity: Activity) : AlertDialog.Builder(activity) {

    private lateinit var binding: CustomAlertBinding

    fun show(isMain: Boolean, onDismiss: () -> Unit){
        val builder = AlertDialog.Builder(activity, R.style.CustomAlertDialog)
            .create()
        val inflater = (activity).layoutInflater
        binding = CustomAlertBinding.inflate(inflater)
        builder.setView(binding.root)
        builder.setCanceledOnTouchOutside(false)
        builder.show()

        binding.cancel.setOnClickListener {
             builder.dismiss()
             onDismiss()
        }
    }
}

相关问题