Search code examples
androidradio-buttonanimatedvectordrawable

android studio - AnimatedVectorDrawable's behave weirdly


I'm trying to insert green ticks on the right side of radio buttons whenever the user checks one of them, but drawables are behaving weirdly.

Initial state(none is checked): enter image description here

then I check the first one, having recovered this one as isVisible=true and the other one isVisible=false: enter image description here

seems ok. Then I check the second one, having recovered this one as isVisible=true and the other one isVisible=false:

enter image description here

A new animation starts on the previous rb and I don't understand why. Then I try to tick the first one again:

enter image description here

A new animation starts at a scrambled position. Then I tick the second one again: enter image description here

So my attempts were done either inside the radio group set as horizontal, adding two imageViews , or by creating a new LinearLayout which I overlapped to the radio group so that the ticks were in the right position according to the RB's.

Programmatically, I tried both either creating two AnimatedVectorDrawable objects for each RB or one shared between the two, with no success.

private lateinit var rb1: RadioButton
    private lateinit var rb2: RadioButton
    private lateinit var rb_1_checked: ImageView
    private lateinit var rb_2_checked: ImageView
    private var rb1_done: AnimatedVectorDrawable? = null
    private var rb2_done: AnimatedVectorDrawable? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.mylayout)
        rb1 = findViewById(R.id.rb_1_id)
        rb2 = findViewById(R.id.rb_2_id)
        rb_1_checked = findViewById(R.id.IV_1_id)
        rb_2_checked = findViewById(R.id.IV_2_id)
        rb1_done =
            AppCompatResources.getDrawable(this, R.drawable.avd_done) as AnimatedVectorDrawable
        rb2_done =
            AppCompatResources.getDrawable(this, R.drawable.avd_done) as AnimatedVectorDrawable
        rb1.setOnCheckedChangeListener { buttonView, isChecked ->
            rb_1_checked.isVisible = true
            rb_2_checked.isVisible = false
            rb_1_checked.setImageDrawable(rb1_done)
            rb1_done!!.start()
        }
        rb2.setOnCheckedChangeListener { buttonView, isChecked ->
            rb_1_checked.isVisible = false
            rb_2_checked.isVisible = true
            rb_2_checked.setImageDrawable(rb2_done)
            rb2_done!!.start()
        }
    }

what am I doing wrong?


Solution

  • I've solved it by changing setOnCheckedChangeListener to setOnClickListener, and also changed isVisible with isInvisible to keep position of the ticks