android 如何在自定义DialogFragment中使用ViewModel中的项信息?

vi4fp9gy  于 2022-12-02  发布在  Android
关注(0)|答案(1)|浏览(362)

我有一个自定义的DialogFragment,它更新RecyclerView项目的数量,主要问题是,积极的按钮没有显示,因为它是在lifecycleScope.launch内初始化。
那么,构建一个使用从数据库中获取的数据的对话框的最佳方法是什么呢?
我的对话框如下所示:

class InputDialog : DialogFragment() {
    private val viewModel: DocumentProductsViewModel by activityViewModels()

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(requireContext())
            val view = layoutInflater.inflate(R.layout.dialog_quantity_input, null)
            val edQuantity: EditText = view.findViewById(R.id.quantity)

            isCancelable = false

            var currentProductId: Long? = null

            val bundle: Bundle? = arguments
            if (bundle != null) {
                currentProductId = bundle.getLong(PRODUCT_ID)
            }

            builder.setView(view)

            currentProductId?.let {
                lifecycleScope.launch {
                    val currentProduct = viewModel.getProductForId(currentProductId)
                    edQuantity.setText(currentProduct?.quantity?.formatForQta())

                    builder.setPositiveButton("Conferma") { _, _ ->
                        hideKeyboard(edQuantity)

                        val quantity = edQuantity.text.toString()
                        if (!isQuantityValid(quantity)) {
                            hideKeyboard(edQuantity)
                            return@setPositiveButton
                        }
                        updateQuantity(currentProduct, quantity)
                    }

                    edQuantity.setOnEditorActionListener { _, actionId, _ ->
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            hideKeyboard(edQuantity)

                            val quantity = edQuantity.text.toString()
                            if (!isQuantityValid(quantity)) {
                                hideKeyboard(edQuantity)
                                dismiss()
                                return@setOnEditorActionListener false
                            }
                            updateQuantity(currentProduct, quantity)
                        }
                        true
                    }

                }
            }

            builder.setTitle("Modifica quantità")

            builder.setNegativeButton("Annulla") { _, _ ->
                hideKeyboard(edQuantity)
            }

            edQuantity.filters = arrayOf(DecimalDigitsInputFilter(4, 3))

            edQuantity.requestFocus()

            val dialog = builder.create()
            dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

            return dialog
        } ?: throw IllegalStateException("Activity cannot be null")
    }

    private fun updateQuantity(product: DocumentProduct?, value: String) {
        val quantity = value.trim().replace(",", ".").toFloat()
        product?.quantity = quantity
        viewModel.update(product)
        dismiss()
    }

    private fun hideKeyboard(v: View) {
        val im: InputMethodManager =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        im.hideSoftInputFromWindow(v.windowToken, 0)
    }

    companion object {
        const val TAG = "InputDialog"
        private const val PRODUCT_ID = "product id"

        fun newInstance(productId: Long) = InputDialog().apply {
            arguments = Bundle().apply {
                putLong(PRODUCT_ID, productId)
            }
        }
    }
}
ct2axkht

ct2axkht1#

您需要在单击按钮时启动协程。

currentProductId?.let {
  val currentProduct = viewModel.getProductForId(currentProductId)
  edQuantity.setText(currentProduct?.quantity?.formatForQta())

  builder.setPositiveButton("Conferma") { _, _ ->
    lifecycleScope.launch {
      hideKeyboard(edQuantity)

      val quantity = edQuantity.text.toString()
      if (!isQuantityValid(quantity)) {
        hideKeyboard(edQuantity)
        return@setPositiveButton
      }
      updateQuantity(currentProduct, quantity)
    }
  }

  edQuantity.setOnEditorActionListener { _, actionId, _ ->
    lifecycleScope.launch {
      if (actionId == EditorInfo.IME_ACTION_DONE) {
        hideKeyboard(edQuantity)

        val quantity = edQuantity.text.toString()
        if (!isQuantityValid(quantity)) {
          hideKeyboard(edQuantity)
          dismiss()
          return@setOnEditorActionListener false
        }
        updateQuantity(currentProduct, quantity)
      }
    }
    true
  }
}

相关问题