从现有数组列表创建数组范围

时间:2019-12-22 18:44:04

标签: android arrays kotlin

我是Kotlin的新手,无法正常工作 我有一个叫做句子数组的数组

val sentenceArray = arrayOfNulls<String>(7)
    sentenceArray[0] = "This is Sentence 0"
    sentenceArray[1] = "This is Sentence 1"
    sentenceArray[2] = "This is Sentence 2"
    sentenceArray[3] = "This is Sentence 3"
    sentenceArray[4] = "This is Sentence 4"
    sentenceArray[5] = "This is Sentence 5"
    sentenceArray[6] = "This is Sentence 6"

我有2个微调器,分别称为leftSpinner和rightSpinner,数组从0到6

val leftSpinnerArray = arrayOf("0", "1", "2", "3", "4", "5", "6")
val rightSpinnerArray = arrayOf("0", "1", "2", "3", "4", "5", "6")

用户为左右微调器选择一个值,它们存储在selectedLeftSpinner和selectedRightSpinner中

val selectedLeftSpinner = leftSpinner.getItemAtPosition(position).toString()
val selectedRightSpinner = rightSpinner.getItemAtPosition(position).toString()

我正在尝试做的事情:

当用户为左侧Spinner选择1并为右侧Spinner选择3时。我希望文本视图在单击按钮后显示“这是句子1,这是句子2,这是句子3”

会发生什么:

现在我有这段代码可以根据现有的数组根据左右微调器的值生成一个数组,但是它不符合我的想法

val list = sentenceArray[selectedLeftSpinner.toInt()] to (sentenceArray[selectedRightSpinner.toInt()])
textView.text = list.toString()

当用户为左侧Spinner选择1并为右侧Spinner选择6时 它在文本视图中显示“这是句子1,这是句子6”。请帮忙!我尝试将其替换为rangeTo,但出现错误。我不确定该怎么做。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用这样的切片

val right=selectedRightSpinner.toInt()
val left=selectedLeftSpinner.toInt()
val list=sentenceArray.slice(left..right)