title: kotlin global activity View reference to use in fragments
body: <p>I'm creating a podcast app with a single activity consisting of 2 elements:</p>
  
  <ul>
  <li>NavHostFragment</li>
  <li>ExoPlayerView (in this case just the PlayerControlView with Id exoplayer_view)</li>
  </ul>
  
  <p>I would like to set up a global variable with a reference to the exoplayer view, so I can use this variable within my fragments and attached viewmodels to play/stop/load audio. How would I implement this efficiently in kotlin?</p>
  
  <p>Right now, whenever I need the exoplayer within a fragment I recreate an variable like this: </p>
  
  <pre><code>var exoplayerView = (activity as MainActivity).exoplayer_view
  </code></pre>
  
  <p>By setting up a global variable in the activity, I don't have to do this again and again all over the app. This is also probably less memory exhaustive than creating another reference in every fragment/viewmodel.</p>
  
  <p>MainActivity:</p>
  
  <pre><code>...
  import kotlinx.android.synthetic.main.activity_main.*
  
  class MainActivity : AppCompatActivity() {
  
      // global reference to use for all fragments, viewmodels and helper classes
      var exoplayerView: PlayerControlView = exoplayer_view
  
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)
  
          ....
      }
  
      override fun onStop() {
          super.onStop()
          releasePlayer(exoplayer_view)
      }
  }
  </code></pre>
  
  <p>Fragment:</p>
  
  <pre><code>class TracksFragment : Fragment() {
  
      override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                savedInstanceState: Bundle?): View? {
          ...
          // make use of exoplayer reference within the fragment and/or viewmodel
          // the exoplayerView variable can not be recognised here
          if(exoplayerView.player==null) exoplayerView.player = viewModel.player
          ...
  
          return binding.root
      }
  }
  </code></pre>
  
  <p>I thought by setting up the exoplayerView reference like this I would be able to reach it from my fragment. However it doesn't. How could I do something like this in a efficient way?</p>