在添加内容之前必须先调用requestFeature(),而在Android中必须先调用requestFeature()

时间:2019-06-17 05:06:22

标签: android kotlin android-alertdialog android-dialog

我有一个这样的对话框

val buyDialog = Dialog(activity)
buyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE) //the stacktrace points here

        buyDialog.setContentView(R.layout.dialog_buy_items)
        buyDialog.setTitle("Buy Items")
        buyDialog.setCancelable(false)
        buyDialog.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val buy_items_cancel = buyDialog.buy_items_cancel


        showSoftKeyboard(buy_items_root, false)
        showProgress(buy_items_progress, false)

        buy_items_cancel.setOnClickListener {
            buyDialog.cancel()
            buyDialog.dismiss()
        }

        buyDialog.show()

这是第一次正常工作。因此,当我通过单击“取消”按钮来取消对话框,然后再次打开该对话框时,我得到了错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.zepling.nepsetrainer, PID: 27676
    android.util.AndroidRuntimeException: requestFeature() must be called before adding content
        at com.android.internal.policy.PhoneWindow.requestFeature(PhoneWindow.java:343)

我正在从这样的另一个AlertDialog调用此对话框

val builder = activity?.let { AlertDialog.Builder(it) }

            builder?.setTitle("Buy Items")
            builder?.setMessage("Do you want to buy available items?")

            builder?.setPositiveButton("YES") { dialog, _ ->

                showBuyItemsDialog()

            }

            builder?.setNegativeButton("No") { dialog, _ ->
                dialog.dismiss()
            }

            val alertDialog: AlertDialog = builder!!.create()

            alertDialog.show()

错误指向buyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)

我在做什么错?任何帮助,将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

针对两种不同情况有两种可能的解决方案:

  1. 在您的代码中,如果您将活动用作对话框,则buyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)将不起作用。扩展Activity而不是ActionBarActivity,它应该可以解决问题。
  2. 如果您使用的是AppCompat,则必须在requestFeature()之前致电super.onCreate()

答案 1 :(得分:0)

如果使用 kotlin ,您可以测试此代码

val buyDialog = Dialog(activity)
    buyDialog.ownerActivity?.requestWindowFeature(Window.FEATURE_NO_TITLE)