我是学习Android的Kotlin的大手笔,我开始在学习过程中创建一个小应用程序,我的问题是:
1-如果我使用以下方法创建图像数组并调用它:
var Images = intArrayOf(R.drawable.PHGLHB_356,R.drawable.PHGLFY145,R.drawable.basket10,R.drawable.basket2,R.drawable.basket3)
var index_image = 0
当我想创建字符串列表时该怎么做?
var Textes = ArrayList(R.string.text1,R.string.text2,R.string.text3,R.string.text4,R.string.text5)
var index_text = 0
2-我还具有以下功能来设置图像源(以下是我尝试的代码):
fun ChangeImage(view: View){
var image_view = findViewById(R.id.image_view) as ImageView
image_view.setImageResource(Images[index_image])
index_image++
if (index_image == Images.size){
index_image = 0
}
}
3-获取文本的方法(下面是我尝试的代码):
fun ChangeText(view: TextView) {
var text_view = findViewById(R.id.text_view) as TextView
text_view.setText(Textes[index_text])
index_text++
if (index_text == Textes.size) {
index_text = 0
}
}
感谢您的宝贵帮助!
答案 0 :(得分:2)
此数组:
var Images = intArrayOf(R.drawable.PHGLHB_356, R.drawable.PHGLFY145,R.drawable.basket10,R.drawable.basket2,R.drawable.basket3)
不是图像数组,而是与drawables id对应的整数数组。
同样,此数组列表(如果已正确初始化):
var Textes = ArrayList(R.string.text1,R.string.text2,R.string.text3,R.string.text4,R.string.text5)
不是字符串的数组列表,而是与资源中存储的字符串的id对应的整数数组。
因此,您可以像其他数组一样使用intArrayOf
而不是ArrayList
,因为这种方式更像是Kotlin:
var Textes = intArrayOf(R.string.text1,R.string.text2,R.string.text3,R.string.text4,R.string.text5)
您的两个函数在语法上都是正确的,尽管最好编写这样的findViewById()
方法:
var image_view = findViewById<ImageView>(R.id.image_view)
和
var text_view = findViewById<TextView>(R.id.text_view)
如果您的导入中有这样的行,则甚至不需要使用findViewById()
:
import kotlinx.android.synthetic.main.activity_main.*
如果这样做,则可以访问image_view
和text_view
,而无需使用findViewById()
查找它们。