Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Icon not showing in FloatingActionButton after changed programmatically

I have an AppCompatActivity with a TabLayout and a FloatingActionButton that I change it's icons depending on which tab is currently displaying.

When I programmatically change the drawable of FloatingActionButton using setImageDrawable or setImageResource, the new icon does not show up, just the blank background of the button.

Strangely enough, if I hide and show the FloatingActionButton after I programmatically changed it's icon, it shows up.

This is the part where I change the icon:

mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout) {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            switch (position) {
                case 0: 
                    floatingActionButton.setImageDrawable(ContextCompat.getDrawable(mMainActivity, R.drawable.ic_save_24dp));
                    if (!floatingActionButton.isShown()) floatingActionButton.show(); 
                    mNavigationView.getMenu().getItem(1).setChecked(true);
                    break;
                case 1: 
                    floatingActionButton.setImageDrawable(ContextCompat.getDrawable(mMainActivity, R.drawable.ic_add_24dp));
                    if (!floatingActionButton.isShown()) floatingActionButton.show(); 
                    mNavigationView.getMenu().getItem(2).setChecked(true);
                    break;
                case 2: 
                    floatingActionButton.hide(); 
                    mNavigationView.getMenu().getItem(3).setChecked(true);
                    break; 
            }
        }
    });

Before:

before

After I programmatically changed it to a "plus" vector drawable:

result

Expected:

expected

So, my question is: What is causing this, and how can it be solved?

like image 982
M. Samil Atesoglu Avatar asked Jul 17 '26 02:07

M. Samil Atesoglu


1 Answers

I also had this problem and I solved by adding a call to the hide method

 mFloatingActionButton.setImageDrawable(getDrawable(R.drawable.default_fab_icon));
 mFloatingActionButton.hide();
 mFloatingActionButton.show();

I had tried .invalidate() but that did not work. This seems to be a problem when switching fragments. I experienced it whilst using the Navigation AndroidX components.

I don't think this is the best solution but I tried a lot and only this worked - there's no flickering effect.

like image 56
d4c0d312 Avatar answered Jul 20 '26 17:07

d4c0d312



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!