设置Kotlin中的ImageView事件



我一直试图在Kotlin中的某个ImageView上显示一个随机图像,不幸的是什么都没有发生。对我来说,这看起来合乎逻辑,但我不知道我做错了什么。

这发生在fragment中这是我的onCreateView函数

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
var rootView = inflater.inflate(R.layout.fragment_fragment1, container, false)
val array = intArrayOf(R.mipmap.ic_hello1, R.mipmap.ic_hello2)
val image = rootView.findViewById<ImageView>(R.id.imageView2)
image.setOnFocusChangeListener(object: View.OnFocusChangeListener {
override fun onFocusChange(view:View, hasFocus:Boolean) {
if (hasFocus) image.setImageResource(array.random())
}
})

return rootView
}

Array资源中检索Drawable的正确方法如下:

1。创建资源:

<resources>
<integer-array name="images">
<item>@drawable/image_1</item>              //Drawable reource
<item>@drawable/image_2</item>
</integer-array>
</resources>

2。检索Drawable通过TypedArray:

val images = resources.obtainTypedArray(R.array.images)
imageView.setImageResource(images.getResourceId(index, 0))    //index see below
images.recycle()        //may need

对于您的情况,索引应该是:(0..images.size - 1).random()

演示:https://www.youtube.com/watch?v=04y2J0MqYa0

最新更新