How to change Progress bar image in android

后端 未结 2 1713
遇见更好的自我
遇见更好的自我 2020-12-24 15:45

I would like to change the progress bar to a custom drawable. How do I change the image of the progress bar?

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 16:27

    You can create a class by extending ImageView and use it like following in a similar way to ProgressBar with a rotation animation.

    class CustomProgressBar : AppCompatImageView {
    
    constructor(context: Context) : super(context)
    
    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
    
    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr)
    
    private var anim: RotateAnimation? = null
    
    init {
        setImageResource(R.drawable.your_custom_drawable)
        anim = RotateAnimation(
            0f, 350f, Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f
        )
        anim!!.interpolator = LinearInterpolator()
        anim!!.repeatCount = Animation.INFINITE
        anim!!.duration = 1000
        startAnimation(anim)
    }
    
    fun getRotateAnimation(): RotateAnimation? {
        return anim
    }}
    

    And in your layout.xml just use this class as your ProgressBar

                
    

    And in your fragment or activity show or hide it like following:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        customProgressBar = findViewById(R.id.customProgressBar)
    }
    
    fun showCustomProgressBar() {
        customProgressBar.visibility = VISIBLE
        customProgressBar.startAnimation(customProgressBar.getRotateAnimation())
    }
    
    fun hideCustomProgressBar() {
        customProgressBar.visibility = GONE
        customProgressBar.clearAnimation()
    }
    

提交回复
热议问题