kotlin 如何处理对话框片段中按下的后退按钮?

a64a0gku  于 2022-12-13  发布在  Kotlin
关注(0)|答案(3)|浏览(161)

我是一个新手,我的应用程序有一个主活动和一个测试活动。通常在测试活动中按下后退按钮会返回到主活动。这没问题,但我想添加一个确认对话框,询问他们是否真的想先放弃测试。到目前为止,我在测试活动中有以下内容:

override fun onBackPressed() {
        var exit = ExitTestDialogFragment()
        exit.show(supportFragmentManager,"exit")

    }

    class ExitTestDialogFragment : DialogFragment() {

        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            return activity?.let {
                val builder = AlertDialog.Builder(it)
                builder.setTitle("Leave Test?")
                builder.setMessage("Your score will be lost.")
                    .setPositiveButton("OK",
                        DialogInterface.OnClickListener { dialog, id ->
                            // This is where I'd like to return to Main Activity
                        })
                    .setNegativeButton("Cancel",
                        DialogInterface.OnClickListener { dialog, id ->
                            dialog.dismiss()// User cancelled the dialog
                        })
                // Create the AlertDialog object and return it
                builder.setCancelable(false)
                builder.create()
            } ?: throw IllegalStateException("Activity cannot be null")
        }
    }

我似乎不知道如何从对话框片段中执行Activity的super.onBackPressed()。就像我说的,我是Android的超级新手,所以可能需要一点ELI5的答案。

1tu0hz3e

1tu0hz3e1#

DialogInterface.OnClickListener中调用finish()this.finish()方法finish()将破坏调用它当前活动,在本例中是test-taking activity

j9per5c4

j9per5c42#

您应该从对话框positive Button中调用mainActivity。

.setPositiveButton("OK",
                    DialogInterface.OnClickListener { dialog, id ->
                        // here you can get your current activity                         
                       //then dismiss your dialog and finish current activity
                       //call context.finish or activity.finish here. It will 
                      //finish this activity    
                    //and will take you to the previous activity (in your case 
                    //to mainActivity)

})如果您需要任何进一步的帮助,请随时在评论中提及

unftdfkk

unftdfkk3#

将此添加到容器对话框中

dialog?.setOnKeyListener { dialog, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {
            handleBack() // your code
            return@setOnKeyListener true
        } else
            return@setOnKeyListener false
    }

相关问题