有没有办法做到2000 else if语句呢?

时间:2019-12-12 11:15:44

标签: android arrays if-statement kotlin

我正在Android Studio中为我的业务创建一个签入条形码应用程序。有2000个。成员在editText中输入其6位数的成员编号,单击“保存”,这将触发下面的saveToMain。我的计划是仅对每张会员卡使用else if。 Kotlin不喜欢这样,并且在其中大约200个之后一直崩溃。我对编码很陌生,只是从字面上学习了此应用程序的语言,所以我几乎一无所知,因此,这可能很疯狂,并且可能有一种更简单的方法。在过去的两个小时中,我一直在Internet上进行搜索,但似乎找不到与这种情况相同的任何内容。您不能为此使用数组,对吗?

下面的R.drawable.a0001文件是与其会员编号相对应的条形码图像。

fun alertDiag() {
    val alertDialog =
        AlertDialog.Builder(this).create()
    alertDialog.setTitle("No Card Entered")
    alertDialog.setMessage("Please use 'Current Membership Card' for your previously saved Membership Card.")
    alertDialog.setButton(
        AlertDialog.BUTTON_POSITIVE,
        "OK"
    ) { dialog, which ->

    }

    alertDialog.show()
}


fun saveToMain(view: View) {
    val editText = findViewById<EditText>(R.id.editText)
    val message = editText.text.toString()
    val image2 = findViewById<View>(R.id.imageView2)

    if (message == "") {
        alertDiag() }
    else if (message == "100001") {image2.setBackgroundResource(R.drawable.a0001);saveToStorage(view);goToGallery(view)}
    else if (message == "100002") {image2.setBackgroundResource(R.drawable.a0002);saveToStorage(view);goToGallery(view)}
    else if (message == "100003") {image2.setBackgroundResource(R.drawable.a0003);saveToStorage(view);goToGallery(view)}
    else if (message == "100004") {image2.setBackgroundResource(R.drawable.a0004);saveToStorage(view);goToGallery(view)}
    else {
        image2.setBackgroundResource(R.drawable.notfound)
    }
}

否则,如果

1 个答案:

答案 0 :(得分:3)

您可以编写一个使用反射来检索可绘制对象的Int ID(R.drawable.whatever值)的函数。

fun findDrawableIdByName(name: String): Int? {
    return try {
        R.drawable::class.java.getField(name).getInt(null)
    } catch (e: NoSuchFieldException){
        null
    }
}

然后假设您的消息值在连续范围内,则可以将它们全部合并为一个else块。

fun saveToMain(view: View) {
    val editText = findViewById<EditText>(R.id.editText)
    val message = editText.text.toString()
    val image2 = findViewById<View>(R.id.imageView2)

    if (message == "") {
        alertDiag() 
    } else if (message.toIntOrNull() in 100001..102000) {
        val name = message.replaceRange(0, 2, "a") // replace the beginning 10 with "a"
        val drawableId = findDrawableIdByName(name)
        if (drawableId == null) {
            image2.setBackgroundResource(R.drawable.notfound)
        } else {
            image2.setBackgroundResource(drawableId)
            saveToStorage(view)
            goToGallery(view)
        }
    } else {
        image2.setBackgroundResource(R.drawable.notfound)
    }
}