Skip to content

Instantly share code, notes, and snippets.

@kgilmer
Created August 22, 2018 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgilmer/07c81866728e441b9bcec8b19fadfb22 to your computer and use it in GitHub Desktop.
Save kgilmer/07c81866728e441b9bcec8b19fadfb22 to your computer and use it in GitHub Desktop.
uamp Kotlin Version
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Since UAMP is a music player, the volume controls should adjust the music volume while
// in the app.
volumeControlStream = AudioManager.STREAM_MUSIC
viewModel = ViewModelProviders
.of(this, InjectorUtils.provideMainActivityViewModel(this))
.get(MainActivityViewModel::class.java)
/**
* Observe changes to the [MainActivityViewModel.rootMediaId]. When the app starts,
* and the UI connects to [MusicService], this will be updated and the app will show
* the initial list of media items.
*/
viewModel.rootMediaId.observe(this,
Observer<String> { rootMediaId ->
if (rootMediaId != null) {
navigateToMediaItem(rootMediaId)
}
})
/**
* Observe [MainActivityViewModel.navigateToMediaItem] for [Event]s indicating
* the user has requested to browse to a different [MediaItemData].
*/
viewModel.navigateToMediaItem.observe(this, Observer {
it?.getContentIfNotHandled()?.let { mediaId ->
navigateToMediaItem(mediaId)
}
})
}
private fun navigateToMediaItem(mediaId: String) {
var fragment: MediaItemFragment? = getBrowseFragment(mediaId)
if (fragment == null) {
fragment = MediaItemFragment.newInstance(mediaId)
supportFragmentManager.beginTransaction()
.apply {
replace(R.id.browseFragment, fragment, mediaId)
// If this is not the top level media (root), we add it to the fragment
// back stack, so that actionbar toggle and Back will work appropriately:
if (!isRootId(mediaId)) {
addToBackStack(null)
}
}
.commit()
}
}
private fun isRootId(mediaId: String) = mediaId == viewModel.rootMediaId.value
private fun getBrowseFragment(mediaId: String): MediaItemFragment? {
return supportFragmentManager.findFragmentByTag(mediaId) as MediaItemFragment?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment