[英]How to change the image on a FloatingActionButton?
在 Kotlin 中,我試圖在單擊時更改浮動操作按鈕上的圖像,以便它在 Y 軸上旋轉並顯示不同的圖像和背景顏色。
我的代碼是這樣的:
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
}
})
我的晶圓廠是這樣初始化和旋轉的:
val fab: View = findViewById(R.id.fab)
fab.setOnClickListener { view ->
rotateFabOnYAxis(fab, this)
}
和 the.xml,其中 fab id 是:
<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" />
我讀過很多不同的答案,說要使用getImageDrawable()
、 setImageResource()
或setImageBitmap()
但我的晶圓廠沒有這些功能可用,所以我有點難過。 在我的代碼中,我試圖直接訪問 fab.background 屬性,但它也不起作用。
此外,晶圓廠確實在 Y 軸上旋轉了 180 度,但它保持了原始圖像
我錯過了什么嗎?
謝謝。
我設法弄明白了。
我的 fab 被顯式轉換為 View,而不是 ImageView。
將View
更改為ImageView
后,我就可以訪問setImageDrawbable()
function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.