2017-10-12 6 views
0

에서 안드로이드의 ID 자원을 얻기 내가 가진 일부 ImageViews (activity_main.xml에서) : imageView_0, imageView_1, imageView_2imageView_3.내 코 틀린 응용 프로그램에서 문자열

0에서 3까지의 루프에서 뷰에 어떻게 액세스 할 수 있습니까? 이 작동하지 않습니다

val imageView: ImageView = findViewById<ImageView>("R.id.imageView_" + index) as ImageView 

답변

4
for(i in 1..3){ 
    val id: int=getResources().getIdentifier("imageview_"+i, "id", 
    getPackageName()) 
    imageview[i]=findViewById(id) as ImageView 
} 

당신은 xml, 내가이 일을 결국 imageview_3

0

imageview_1, imageview_2가에있는 경우 : 다른 옵션은 허용

var imageViews: Array<ImageView?> = arrayOfNulls(4) 

for (i in 0..3) { 
    val id: Int = getResources().getIdentifier("imageView_" + i, "id", getPackageName()) 
    imageViews.set(i, findViewById<ImageView>(id) as ImageView) 
} 
1

null이 아닌 배열을 선언하려면 ImageView s :

val imageViews : Array<ImageView> = Array(4, { 
    val id: Int = resources.getIdentifier("imageView_" + it, "id", packageName) 
    findViewById<ImageView>(id) 
})