title: Is there a way to have a floating action button do something dependant on which fragment is currently in nav host?
body: <p>I'm having some trouble with a single activity project. There is a floating action button in MainActivity that I want to use in several fragments. So if HomeFragment is in the nav_host_fragment, I want the floating action button to do thing1, and if SecondFragment is in nav_host_fragment, I want the floating action button to do thing2.</p>
  <p>If you create a new project in android studio and select basic activity you'll get the code I'm working with.
  There is a MainActivity, two fragments (FirstFragment and SecondFragment) and a Navigation controller. FirstFragment is displayed first, and this is where I want the action button to invoke method <code>doThing1()</code>. If you click on the button in this fragment it takes you to SecondFragment. If you click the floating action button now, I would like the fab to invoke <code>doThing2()</code>
  How would I go about this?</p>
  <p>I've tried</p>
  <p>In the fragments</p>
  <pre><code>
     public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
             super.onViewCreated(view, savedInstanceState);`
     
     view.findViewById(R.id.button_first).setOnClickListener(v -&gt; {
     doThing1();
      });
  
  </code></pre>
  <p>But this doesn't work because <code>findViewById</code> doesn't find the fab, I guess because it's searching in the fragments own layout and not in the main activity.</p>
  <p>The only way I solved this is by getting a reference to MainActivity in the fragment, invoke a public method from MainActivity and set a field (to &quot;first&quot; or something similar) and then in the fab onClick method check what this variable is set to and execute different methods dependant on this variable.</p>
  <p>So in <code>onViewCreated</code>:</p>
  <pre><code>MainActivity reference = (MainActivity) getActivity();
  assert reference != null;
  reference.changeFabActionTo(&quot;thing2&quot;);
  </code></pre>
  <p>And then in the click listener</p>
  <pre><code>fab.setOnClickListener(view -&gt; {
                  if(whichFragmentClick.equals(&quot;thing1&quot;)) {
                      // doThing1()}
                  if(whichFragmentClick.equals(&quot;thing2&quot;)) {
                      // doThing2()}
              });
  </code></pre>
  <p>This doesn't seem like the way to go about this however, and I feel like this isn't the proper way.
  Any ideas?</p>