in ClassicsKotlin/app/src/main/java/com/android/tv/classics/fragments/MediaBrowserFragment.kt [96:166]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = getString(R.string.app_name)
headersState = BrowseSupportFragment.HEADERS_DISABLED
isHeadersTransitionOnBackEnabled = true
// Initialize database connection
database = TvMediaDatabase.getInstance(requireContext())
// Setup this browser fragment's adapter
adapter = ArrayObjectAdapter(ListRowPresenter())
// Each time an item is selected, change the background
setOnItemViewSelectedListener { _, item, _, row ->
if (item == null) return@setOnItemViewSelectedListener
val metadata = item as TvMediaMetadata
Log.d(TAG, "Row selected: ${row.id}. Item selected: ${metadata.id}")
// Launch the background tint update task in a coroutine
lifecycleScope.launch(Dispatchers.IO) {
metadata.artUri?.let { artUri ->
Coil.get(artUri) { allowHardware(false) }.toBitmap()
}?.let { artBitmap ->
Palette.Builder(artBitmap).generate {
// Extract dominant color from the generated palette
val dominantColor =
it?.getDominantColor(currentTintColor) ?: currentTintColor
// Modify color's alpha channel to make it partly transparent
val backgroundColor =
ColorUtils.setAlphaComponent(dominantColor, BACKGROUND_TINT_ALPHA)
// Set the partly transparent dominant color as the background tint
Log.d(TAG, "Using dominant color for background tint: $backgroundColor")
updateBackgroundTint(backgroundColor)
}
}
}
}
// When user clicks on an item, navigate to the now playing screen
setOnItemViewClickedListener { _, item, _, _ ->
val metadata = item as TvMediaMetadata
Navigation.findNavController(
requireActivity(), R.id.fragment_container).navigate(
MediaBrowserFragmentDirections.actionToNowPlaying(metadata))
}
// Instantiate the credits row, which will be added to the adapter inside [populateAdapter]
creditsRow = ListRow(HeaderItem(getString(R.string.credits)), object : ObjectAdapter() {
override fun size(): Int = 0
override fun get(position: Int): Any? = null
})
// Keep track of the synchronization work so we can join it later
synchronizeJob = lifecycleScope.launch(Dispatchers.IO) {
// Now that the fragment has been created, we can populate our adapter
populateAdapter(adapter as ArrayObjectAdapter)
// Start a one-off synchronization job when fragment is shown, bypassing work manager
TvMediaSynchronizer.synchronize(requireContext())
}
// Pick a random background for our fragment
backgroundDrawable = lifecycleScope.async(Dispatchers.IO) {
val backgroundUrl = database.backgrounds().findAll().shuffled().firstOrNull()?.uri
Coil.getAny(backgroundUrl ?: R.mipmap.bg_browse_fallback)
}
}