Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle FloatingActionButton Icon when Clicking On It

I have two drawable pictures, initially FAB is set to R.drawable.icon1, I want to set it to R.drawable.icon2 when clicking on it, and setting it back to icon1 when clicking one more time on it and so on...

Is there a way to do that?

Any help is appreciated!

like image 527
Bisma Frühling Avatar asked Dec 24 '22 15:12

Bisma Frühling


1 Answers

Hope this helps, we have a boolean flag which denotes the current icon visible in your fab.

FloatingActionButton fab;
boolean flag = true; // true if first icon is visible, false if second one is visible.

fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(flag){

                fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon2));
                flag = false;

            }else if(!flag){

                fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon1));
                flag = true;

            }

        }
    });
like image 113
Chirag Avatar answered Jan 18 '23 08:01

Chirag