title: Kotlin - Call fragment method from MainActivity
body: <p>I have two fragments and a toolbar with a menu. I want to be able to switch fragments when a menu item is selected by calling the method in the fragment that does this. Problem is, I get this error when I try running the app with the code below. <code>java.lang.IllegalStateException: Fragment FirstFragment{5ce330b (f5c2d362-d3fb-4346-9971-dd7be653e609)} not associated with a fragment manager.</code></p>
  <p>MainActivity.kt</p>
  <pre><code>class MainActivity : AppCompatActivity() {
  
      lateinit var adapter: Adapter
  
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)
          setSupportActionBar(findViewById(R.id.toolbar))
      }
  
  
      override fun onCreateOptionsMenu(menu: Menu): Boolean {
          // Inflate the menu; this adds items to the action bar if it is present.
          menuInflater.inflate(R.menu.menu_main, menu)
  
          return true
      }
  
      override fun onOptionsItemSelected(item: MenuItem): Boolean {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          return when (item.itemId) {
              R.id.action_settings -&gt; {
                  FirstFragment().settings()
                  true
              }
  
              else -&gt; super.onOptionsItemSelected(item)
  
          }
      }
  }
  </code></pre>
  <p>FirstFragment.kt</p>
  <pre><code>fun settings() {
      findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
  }
  </code></pre>
  <p>How can I implement a fragment manager so I can call this method via MenuItem and not get an exception? Thanks in advance!</p>