首页 > 解决方案 > 如何制作一个用于验证 TextInputLayout kotlin 的函数

问题描述

我想制作一个用于验证文本输入(材料设计)的功能并多次使用它
我有一个工作代码但我知道它很脏
如何优化它?
这是我的 onClick 方法

 fun addItems(view: View) {

        val name1 = etName.text.toString().trim()
        val quantity1 = etQuantity.text.toString()
        val gst1 = etGst.text.toString()
        val amount1 = etAmount.text.toString()
        fun showToast() {
            runOnUiThread(kotlinx.coroutines.Runnable {
                Toast.makeText(this, "$name1 Added", Toast.LENGTH_LONG).show()
            }) // runnable is used because activity is immediately killed and toast cannot be sowed hence it is to be done on ui tread
            finish()
        }

        if (name1.isNotBlank() && quantity1.isNotBlank() && amount1.isNotBlank()) {

            if (quantity1.toInt() != 0) {
                if (amount1.toInt() != 0) {
                    Thread {
                        val db = Room.databaseBuilder(this, AppDb::class.java, "BookDB")
                            .build()
                        val item = ItemEntity()
                        item.itemName = name1
                        item.quantity = quantity1
                        item.amount = amount1
                        if (boolProcessWithGST) {
                            if (gst1.isNotBlank()) {
                                if (gst1.toInt() != 0) {
                                    // process with GST
                                    item.gst = gst1
                                    db.abstractItemDao().saveItems(item)
                                    showToast()

                                } else runOnUiThread {
                                    tilGST.error = "Tax can't be 0%"
                                    etGst.requestFocus()
                                } // ui operation only works on main/ui thread
                            } else runOnUiThread {
                                tilGST.error = "Disable toggle if no TAX"
                                etGst.requestFocus()
                            }
                        } else {
                            // process without gst
                            db.abstractItemDao().saveItems(item)
                            showToast()
                        }
                    }.start()
                } else {
                    tilAmount.error = "Amount can't be 0"
                    etAmount.requestFocus()
                }
            } else {
                tilQuantity.error = "Quantity can't be 0"
                etQuantity.requestFocus()
            }
        } else Toast.makeText(this, "please fill the required fields", Toast.LENGTH_LONG).show()
    }

我想对同一活动中的另一个 onClick 使用相同的验证

我尝试制作一个函数,但 android studio 建议 -> Cascade if 应该替换为 when。怎么做?
我做的功能

private fun isValidInput(): Boolean {
        var isValid = true
        val name1 = etName.text.toString().trim()
        val quantity1 = etQuantity.text.toString()
        val gst1 = etGst.text.toString()
        val amount1 = etAmount.text.toString()

        TransitionManager.beginDelayedTransition(root_layout)
        if (name1.isEmpty()) {
            tilName.isErrorEnabled = true
            tilName.error = "Required"
            isValid = false
        } else tilName.isErrorEnabled = false


        if (quantity1.isEmpty()) {
            tilQuantity.isErrorEnabled = true
            tilQuantity.error = "Required"
            isValid = false
        } else if (quantity1.toInt() == 0) {
            tilQuantity.isErrorEnabled = true
            tilQuantity.error = "can't be 0"
        } else tilQuantity.isErrorEnabled = false


        if (amount1.isEmpty()) {
            tilAmount.isErrorEnabled = true
            tilAmount.error = "Required"
            isValid = false
        }else if (amount1.toInt() == 0) {
            tilAmount.isErrorEnabled = true
            tilAmount.error = "can't be 0"
        } else tilAmount.isErrorEnabled = false


        if (gst1.isEmpty()) {
            tilGST.isErrorEnabled = true
            tilGST.error = "Required"
            isValid = false
        }else if (gst1.toInt() == 0) {
            tilGST.isErrorEnabled = true
            tilGST.error = "can't be 0"
        } else tilGST.isErrorEnabled = false

        return isValid
    }

标签: android-studiovalidationkotlinandroid-textinputlayout

解决方案


首先,我建议使用MVVM或任何其他架构模式(MVC、MVP、MVI ...)来清理您的代码并实现关注点分离原则。简而言之,您应该有一个单独的类用于您的应用程序逻辑(在 MVVM 中称为ViewModel)和用于访问和保存您的数据(如数据库或 API 调用)的存储库类,并且您的活动只负责视图。这将使您的代码更干净。
对于初学者,您可以使用本指南:应用程序架构指南,
但还有大量其他资源可供您学习

对于您的警告“Cascade if should be replace with when”,您可以按 Alt+enter 并让 android studio 为您完成。如果它不工作,你可以自己做。它的意思是这样的

如果:

if (num == 0) {
        //do something
    } else if (num < 5) {
        //do something
    } else {
        //do something
    }

转换为 when 看起来像这样:

 when {
        num == 0 -> {
            //do something
        }
        num < 5 -> {
            //do something
        }
        else -> {
            //do something
        }
    }

whenswitch/case在其他编程语言中调用。


推荐阅读