In Kotlin I'm trying to change the image on a floating action button when it's clicked so that it rotates on it's Y axis and shows a different image and background color.
My code is this:
private fun rotateFabOnYAxis(fab: View, context: Context) {
fab.animate().rotationY(180f).setListener(object: Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) {
fab.background = ContextCompat.getDrawable(context, R.drawable.helmet)
}
override fun onAnimationEnd(animation: Animator?) {
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationRepeat(animation: Animator?) {
// This method is called when the animation repeats
}
})
My fab is initialized and rotated like this:
val fab: View = findViewById(R.id.fab)
fab.setOnClickListener { view ->
rotateFabOnYAxis(fab, this)
}
and the.xml where the fab id is:
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:src="@drawable/bike_helmet_plus_1"
android:layout_margin="30dp" />
I've read tons of different answers saying to use getImageDrawable()
, setImageResource()
, or setImageBitmap()
but my fab has none of those functions available so I'm a little stumped. In my code I'm trying to access the fab.background property directly but it's not working either.
Also the fab is indeed rotating 180 degrees in the Y axis, but it maintains the original image
Am I missing something?
Thanks.
I managed to figure it out.
My fab was being explicitly cast into View, rather than ImageView.
After changing View
to ImageView
I was then able to access the setImageDrawbable()
function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.