【问题标题】:How to override onCancel in Dialog Fragment in Android in kotlin?如何在 kotlin 的 Android 中的 Dialog Fragment 中覆盖 onCancel?
【发布时间】:2019-06-16 22:59:40
【问题描述】:

我想显示一个进度条DialogFragment。 它会一直显示,直到它被取消或取消。 如果用户按下后退按钮或触摸对话框外部,它可以被取消,如果用户在任务完成之前没有取消它,它会被关闭。 所以,我想为两者设置listeners,这样我就可以根据情况做出回应。 该对话框是从Fragment 调用的。

根据this,我不能设置listeners,而是必须override的方法。 我的主要问题是,我不知道如何在kotlin 中做到这一点。 我在下面写了一些代码,但它不完整。请在需要的地方更正代码。

我现在只尝试实现onCancel。请务必告知是否需要以某种不同的方式实现 onDismiss。 按照解决方案here, 这就是我编码Fragment的方式:

class MyFragment: Fragment(), DialogInterface.OnCancelListener {

    // other code

    private fun myFun() {
        // show progress dialog
        val myDialog = DialogProgress()
        myDialog.show(childFragmentManager, "null")

        // todo the long task of downloading something
        // myDialog.dismiss()
    }

    override fun onCancel(dialog: DialogInterface?) {
        // User canceled the dialog
        Toast.makeText(activity, "Process canceled by user!", Toast.LENGTH_SHORT).show()
        // todo
    }

}

这是我的DialogFragment 代码:

class DialogProgress: DialogFragment() {

    override fun onCancel(dialog: DialogInterface?) {
        super.onCancel(dialog)
        // need help here
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        super.onCreateDialog(savedInstanceState)

        // show progress dialog
        val v = activity!!.layoutInflater.inflate(R.layout.dialog_progress, null)
        v.findViewById<TextView>(R.id.progress_message).text = "Fetching data"

        return activity!!.let {
            val builder = AlertDialog.Builder(it, R.style.ThemeOverlay_AppCompat_Dialog)
            builder
                .setView(progressView)
                .create()
        }

    }
}

对于上面需要帮助的代码,我不知道如何将上面给出的解决方案链接中的以下Java代码转换为kotlin

@Override
public void onDismiss(final DialogInterface dialog) {
    super.onDismiss(dialog);
    Fragment parentFragment = getParentFragment();
    if (parentFragment instanceof DialogInterface.OnDismissListener) {
        ((DialogInterface.OnDismissListener) parentFragment).onDismiss(dialog);
    } 
}

注意这是给onDismiss的,我要给onCancel

【问题讨论】:

    标签: android kotlin overriding android-dialogfragment


    【解决方案1】:

    只需将 Java 代码粘贴到 Android Studio 中即可将其转换为 kotlin 代码,然后应该会出现一个弹出窗口。 这是java代码的转换:

    override fun onCancel(dialog: DialogInterface?) {
        super.onCancel(dialog)
        val parentFragment = parentFragment
        if (parentFragment is DialogInterface.OnCancelListener) {
            (parentFragment as DialogInterface.OnCancelListener).onCancel(dialog)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多