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:
After I programmatically changed it to a "plus" vector drawable:
Expected:
So, my question is: What is causing this, and how can it be solved?
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.