如果我在xml中设置src,那么背景颜色就可以了。 Here what I expected to receive
在代码中设置我的received
在Kotlin文件中:
fun setImagesToButtons(){
var index: Int
for (i in 0..gameFieldGridLayout.childCount - 1){
index = randomNumber()
ImgResource.imgIdMap.get(index)?.let {
gameFieldGridLayout.getChildAt(i).setBackgroundResource(it)
}
}
}
fun randomNumber(): Int {
return Random().nextInt((6-1) + 1)
}
具有ID的HashMap:
class ImgResource {
companion object {
val imgIdMap: HashMap<Int, Int> = hashMapOf(
1 to R.drawable.i1,
2 to R.drawable.i2,
3 to R.drawable.i3,
4 to R.drawable.i4,
5 to R.drawable.i5,
6 to R.drawable.i6)
}
}
和xml:
<android.support.v7.widget.GridLayout
android:layout_height="match_parent"
app:columnCount="16"
android:layout_width="match_parent"
app:rowCount="9"
android:layout_gravity="center"
android:id="@+id/gameFieldGridLayout">
<ImageButton android:id="@+id/btnCard_1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/background_light"
android:adjustViewBounds="true"
android:visibility="visible"
app:layout_columnWeight="1"
app:layout_rowWeight="1" android:paddingBottom="1dp"
android:paddingTop="1dp"
android:paddingLeft="3dp" android:paddingRight="3dp"
android:layout_margin="1dp"
android:scaleType="centerCrop"
style="@android:style/Widget.DeviceDefault.ImageButton"
android:src="@drawable/i1"/>
请帮助解决此问题! 附言对不起,我的badddd英语!
答案 0 :(得分:0)
您的方法有时返回0,公式为(max - min + 1) + min
fun randomNumber(): Int {
return Random().nextInt((6-1) + 1) + 1
}