如何在AndroidKotlin中从输入获取数组

xtupzzrd  于 2022-11-16  发布在  Kotlin
关注(0)|答案(2)|浏览(146)

我对Kotlin和android整体来说还是个新手。我正在尝试找到一种方法,通过EditText获取输入,并通过按下按钮接受值来将其添加到数组中,但我似乎无法找到它。我尝试了许多选项,似乎没有任何选项对我有效。下面我粘贴了我当前的代码。任何帮助都将非常感谢,因为我目前卡住了。提前感谢!

class MainActivity2 : AppCompatActivity() {
    private lateinit var addnumber: EditText
    private lateinit var storednumber: TextView
    private lateinit var output: TextView
    private lateinit var addbutton: Button
    private lateinit var clearbutton: Button
    private lateinit var averagebutton: Button
    private lateinit var minmaxbutton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        
        
        storednumber = findViewById(R.id.stored_tv)
        output = findViewById(R.id.answer2_tv)
        addbutton = findViewById(R.id.addNum_btn)
        clearbutton = findViewById(R.id.clear_btn)
        averagebutton = findViewById(R.id.average_btn)
        minmaxbutton = findViewById(R.id.minMax_btn)
        addbutton.setOnClickListener {

            val ed = findViewById<View>(R.id.et_addNum) as EditText
            var text = ed.text.toString()
            val arr =
                IntArray(text!!.length / 2) //Assuming no spaces and user is using one comma between numbers

            var i = 0
            while (text != null && text.length > 0) {
                arr[i] = text.substring(0, 1).toInt()
                text = text.substring(text.indexOf(",") + 1)
                i++
            }

        }

    }
}
jtjikinw

jtjikinw1#

我想你在实际的String到Int的转换中遇到了麻烦。我真的建议在这种情况下不要使用while逻辑和子串,因为这会让你的生活变得复杂,而Kotlin已经提供了一种简单的方法来转换数据类型。
Collection transformation operations

fun main() {
    val textBox = "1,2,3"
    if (textBox != null && textBox.length > 0) {
        val intList = textBox.split(",").map { it.toInt() }
        print(intList)
    }
}

或者如果需要IntArray

fun main() {
    val textBox = "1,2,3"
    if (textBox != null && textBox.length > 0) {
        val intArray = textBox.split(",").map { it.toInt() }.toIntArray()
        print(intArray.contentToString())
    }
}
jdzmm42g

jdzmm42g2#

实际使用下面的代码非常容易:

addbutton.setOnClickListener {

            val ed = findViewById<View>(R.id.et_addNum) as EditText
            var text = ed.text.toString()
            val array: List<String> = text.split(",")
            // That's is all you need. Now use this array where you want.
            // Example get 3rd item with array[2]
            // Or loop through it like below
            for (element in array) {
               Log.e("elements", element)
            }
        }

相关问题