Home > Software design >  How to hide the FloatingActionButton that is part of the Activity in the Fragment in Kotlin?
How to hide the FloatingActionButton that is part of the Activity in the Fragment in Kotlin?

Time:11-10

In my 'HomeActivity', I have a FloatingActionButton and four Fragments. I want the FloatingActionButton to be shown only in the 'fragment1' and 'fragment2' make hide it in the 'fragment3' and 'fragment4'. I tried but it didn't work.

Following is what I have in the xml file of the 'HomeActivity'

<?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"
    android:id="@ id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@ id/bottom_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@ id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginEnd="16dp"
            android:background="@android:color/transparent"
            app:menu="@menu/bottom_nav_menu" />

    </com.google.android.material.bottomappbar.BottomAppBar>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@ id/fab_one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_hide_category"
            app:layout_anchor="@id/bottom_appbar"/>

    <fragment
        android:id="@ id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        app:layout_anchor="@id/bottom_appbar"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

I added the below code in the 'HomeActivity'

fun hideFabOne(){
    binding.fabOne.hide()
}

and below code in the onCreateView of the fragments where I want to hide the FAB. But, it didn't work.

HomeActivity().hideFabOne()

CodePudding user response:

Looks like you are creating new instance of activity , try

(requireActivity() as HomeActivity).hideFabOne()

*Add for comment You can modify the hideFabOne() something like

fun hideFabOne(){
    binding.fabOne.visiblity = if( binding.fabOne.isVisible ) View.VISIBLE else View.GONE
}
  • Related