Home > Back-end >  Change Floating Action Button Image Programmatically in DrawerLayout
Change Floating Action Button Image Programmatically in DrawerLayout

Time:10-05

Just as the title suggest, I am trying to change the floating image button's icon/image programmatically when the user open specifics fragment from DrawerLayout. This is what I've alredy tried : First, this is the onCreate() method for the DrawerLayout class.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu_drawer);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), TransaksiKeranjang.class);
            startActivity(intent);
        }
    });
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_transaksi, R.id.nav_pesanan, R.id.nav_sejarah, R.id.nav_inventory,
            R.id.nav_akun, R.id.nav_cabang, R.id.nav_laporan, R.id.nav_logout)
            .setDrawerLayout(drawer)
            .build();
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
    
    //Change fab icon when branch fragment open
    navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
        @Override
        public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
            if (destination.getId() == R.id.nav_cabang) {
                fab.setImageDrawable(ContextCompat.getDrawable(getParent(), R.drawable.icon_add));
            }
        }
    });

    navigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(menuItem -> {
        Intent intent = new Intent(MenuDrawer.this, Login.class);
        startActivity(intent);
        return true;
    });
}

And then this is the xml where floating action button exist :

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@drawable/background_fragment"
 tools:context=".MenuDrawer">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/Theme.HuwenakApp.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@ id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/huwenak_brown"
        app:popupTheme="@style/Theme.HuwenakApp.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@ id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/icon_cart" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

The problem is when I try to change the fab image I always get a nullPointerException error in this line :

fab.setImageDrawable(ContextCompat.getDrawable(getParent(), R.drawable.icon_add));

Which is weird because the onClickListener is working fine and not giving me this error.

CodePudding user response:

You have to add the context

fab.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon_add))

You see in documentation getDrawable need context and if you pass the parent then you get the below error

Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.content.Context.getDrawable(int)' on a null object reference

getDrawable(@NonNull Context context, @DrawableRes int id)
  • Related