Kotlin code refactor

Refactor dialogs
This commit is contained in:
Hemanth S 2020-05-24 03:17:23 +05:30
parent d7aae9270e
commit a5cc0572a8
21 changed files with 371 additions and 384 deletions

View file

@ -54,7 +54,6 @@ class AboutActivity : AbsBaseActivity(), View.OnClickListener {
return json return json
} }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
setDrawUnderStatusBar() setDrawUnderStatusBar()
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View file

@ -15,6 +15,7 @@ import androidx.fragment.app.Fragment
import androidx.fragment.app.commit import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import code.name.monkey.appthemehelper.ThemeStore.Companion.accentColor import code.name.monkey.appthemehelper.ThemeStore.Companion.accentColor
import code.name.monkey.appthemehelper.util.ATHUtil
import code.name.monkey.appthemehelper.util.ATHUtil.resolveColor import code.name.monkey.appthemehelper.util.ATHUtil.resolveColor
import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper
import code.name.monkey.retromusic.* import code.name.monkey.retromusic.*
@ -59,9 +60,11 @@ import com.google.android.play.core.install.InstallState
import com.google.android.play.core.install.InstallStateUpdatedListener import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.InstallStatus.*
import com.google.android.play.core.install.model.UpdateAvailability import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.play.core.tasks.Task import com.google.android.play.core.tasks.Task
import kotlinx.android.synthetic.main.activity_main_content.* import kotlinx.android.synthetic.main.activity_main_content.*
import java.math.BigInteger
import java.util.* import java.util.*
class MainActivity : AbsSlidingMusicPanelActivity(), class MainActivity : AbsSlidingMusicPanelActivity(),
@ -73,7 +76,7 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
} }
lateinit var libraryViewModel: LibraryViewModel lateinit var libraryViewModel: LibraryViewModel
private lateinit var cab: MaterialCab private var cab: MaterialCab? = null
private val intentFilter = IntentFilter(Intent.ACTION_SCREEN_OFF) private val intentFilter = IntentFilter(Intent.ACTION_SCREEN_OFF)
private lateinit var currentFragment: MainActivityFragmentCallbacks private lateinit var currentFragment: MainActivityFragmentCallbacks
private var appUpdateManager: AppUpdateManager? = null private var appUpdateManager: AppUpdateManager? = null
@ -81,10 +84,10 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
private val listener = object : InstallStateUpdatedListener { private val listener = object : InstallStateUpdatedListener {
override fun onStateUpdate(state: InstallState) { override fun onStateUpdate(state: InstallState) {
when { when {
state.installStatus() == InstallStatus.DOWNLOADED -> { state.installStatus() == DOWNLOADED -> {
popupSnackBarForCompleteUpdate() popupSnackBarForCompleteUpdate()
} }
state.installStatus() == InstallStatus.INSTALLED -> { state.installStatus() == INSTALLED -> {
appUpdateManager?.unregisterListener(this) appUpdateManager?.unregisterListener(this)
} }
else -> { else -> {
@ -156,7 +159,7 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
appUpdateManager?.appUpdateInfo appUpdateManager?.appUpdateInfo
?.addOnSuccessListener { appUpdateInfo: AppUpdateInfo -> ?.addOnSuccessListener { appUpdateInfo: AppUpdateInfo ->
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) { if (appUpdateInfo.installStatus() == DOWNLOADED) {
popupSnackBarForCompleteUpdate() popupSnackBarForCompleteUpdate()
} }
try { try {
@ -213,10 +216,7 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
gridSizeItem.setTitle(R.string.action_grid_size_land) gridSizeItem.setTitle(R.string.action_grid_size_land)
} }
setUpGridSizeMenu(fragment, gridSizeItem.subMenu) setUpGridSizeMenu(fragment, gridSizeItem.subMenu)
setupLayoutMenu(fragment, menu.findItem(R.id.action_layout_type).subMenu)
val layoutItem: MenuItem = menu.findItem(R.id.action_layout_type)
setupLayoutMenu(fragment, layoutItem.subMenu)
setUpSortOrderMenu(fragment, menu.findItem(R.id.action_sort_order).subMenu) setUpSortOrderMenu(fragment, menu.findItem(R.id.action_sort_order).subMenu)
} else { } else {
menu.removeItem(R.id.action_layout_type) menu.removeItem(R.id.action_layout_type)
@ -425,8 +425,7 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
R.id.action_album_sort_order_asc, R.id.action_album_sort_order_asc,
0, 0,
R.string.sort_order_a_z R.string.sort_order_a_z
).isChecked = ).isChecked = currentSortOrder == AlbumSortOrder.ALBUM_A_Z
currentSortOrder == AlbumSortOrder.ALBUM_A_Z
sortOrderMenu.add( sortOrderMenu.add(
0, 0,
R.id.action_album_sort_order_desc, R.id.action_album_sort_order_desc,
@ -565,14 +564,11 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data)
if (!hasPermissions()) { if (!hasPermissions()) {
requestPermissions() requestPermissions()
} }
} }
private fun setupToolbar() { private fun setupToolbar() {
toolbar.setBackgroundColor(resolveColor(this, R.attr.colorSurface)) toolbar.setBackgroundColor(resolveColor(this, R.attr.colorSurface))
appBarLayout.setBackgroundColor(resolveColor(this, R.attr.colorSurface)) appBarLayout.setBackgroundColor(resolveColor(this, R.attr.colorSurface))
@ -748,7 +744,7 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
try { try {
id = idString.toLong() id = idString.toLong()
} catch (e: NumberFormatException) { } catch (e: NumberFormatException) {
Log.e(MainActivity.TAG, e.message) Log.e(TAG, e.message)
} }
} }
} }
@ -756,26 +752,29 @@ class MainActivity : AbsSlidingMusicPanelActivity(),
} }
override fun handleBackPress(): Boolean { override fun handleBackPress(): Boolean {
if (cab.isActive) { if (cab != null && cab!!.isActive) {
cab.finish() cab?.finish()
return true return true
} }
return super.handleBackPress() || currentFragment.handleBackPress() return super.handleBackPress() || currentFragment.handleBackPress()
} }
override fun openCab(menuRes: Int, callback: MaterialCab.Callback): MaterialCab { override fun openCab(menuRes: Int, callback: MaterialCab.Callback): MaterialCab {
if (cab != null && cab.isActive) { cab?.let {
cab.finish() if (it.isActive) it.finish()
} }
cab = MaterialCab(this, R.id.cab_stub) cab = MaterialCab(this, R.id.cab_stub)
.setMenu(menuRes) .setMenu(menuRes)
.setCloseDrawableRes(R.drawable.ic_close_white_24dp) .setCloseDrawableRes(R.drawable.ic_close_white_24dp)
.setBackgroundColor( .setBackgroundColor(
RetroColorUtil.shiftBackgroundColorForLightText( RetroColorUtil.shiftBackgroundColorForLightText(
resolveColor(this, R.attr.colorSurface) ATHUtil.resolveColor(
this,
R.attr.colorSurface
)
) )
) )
.start(callback) .start(callback)
return cab return cab as MaterialCab
} }
} }

View file

@ -18,11 +18,11 @@ import android.app.Dialog
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.extensions.extraNotNull
import code.name.monkey.retromusic.loaders.PlaylistLoader import code.name.monkey.retromusic.loaders.PlaylistLoader
import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.PlaylistsUtil import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.list.listItems
class AddToPlaylistDialog : DialogFragment() { class AddToPlaylistDialog : DialogFragment() {
@ -30,34 +30,34 @@ class AddToPlaylistDialog : DialogFragment() {
savedInstanceState: Bundle? savedInstanceState: Bundle?
): Dialog { ): Dialog {
val playlists = PlaylistLoader.getAllPlaylists(requireContext()) val playlists = PlaylistLoader.getAllPlaylists(requireContext())
val playlistNames: MutableList<String> = mutableListOf() val playlistNames = mutableListOf<CharSequence>()
playlistNames.add(requireContext().resources.getString(R.string.action_new_playlist)) playlistNames.add(requireContext().resources.getString(R.string.action_new_playlist))
for (p in playlists) { for (p in playlists) {
playlistNames.add(p.name) playlistNames.add(p.name)
} }
return MaterialDialog(requireContext()).show { return MaterialAlertDialogBuilder(
title(R.string.add_playlist_title) requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
listItems(items = playlistNames) { dialog, index, _ -> )
val songs = .setTitle(R.string.add_playlist_title)
requireArguments().getParcelableArrayList<Song>("songs") ?: return@listItems .setItems(playlistNames.toTypedArray()) { dialog, which ->
if (index == 0) { val songs = extraNotNull<ArrayList<Song>>("songs")
dialog.dismiss() if (which == 0) {
activity?.supportFragmentManager?.let { CreatePlaylistDialog.create(songs.value)
CreatePlaylistDialog.create(songs).show(it, "ADD_TO_PLAYLIST") .show(childFragmentManager, "ADD_TO_PLAYLIST")
} dismiss()
} else { } else {
dialog.dismiss()
PlaylistsUtil.addToPlaylist( PlaylistsUtil.addToPlaylist(
requireContext(), requireContext(),
songs, songs.value,
playlists[index - 1].id, playlists[which - 1].id,
true true
) )
dismiss()
} }
} }
} .create()
} }
companion object { companion object {

View file

@ -20,7 +20,7 @@ import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
class ClearSmartPlaylistDialog : DialogFragment() { class ClearSmartPlaylistDialog : DialogFragment() {
@ -30,23 +30,22 @@ class ClearSmartPlaylistDialog : DialogFragment() {
val playlist = requireArguments().getParcelable<AbsSmartPlaylist>("playlist") val playlist = requireArguments().getParcelable<AbsSmartPlaylist>("playlist")
val title = R.string.clear_playlist_title val title = R.string.clear_playlist_title
val content = HtmlCompat.fromHtml( val message = HtmlCompat.fromHtml(
getString(R.string.clear_playlist_x, playlist!!.name), getString(R.string.clear_playlist_x, playlist!!.name),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
return MaterialDialog(requireContext()).show { return MaterialAlertDialogBuilder(
title(title) requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
message(text = content) )
positiveButton(R.string.clear_action) { .setTitle(title)
if (activity == null) { .setMessage(message)
return@positiveButton .setPositiveButton(R.string.clear_action) { _, _ ->
}
playlist.clear(requireActivity()) playlist.clear(requireActivity())
} }
negativeButton { (android.R.string.cancel) } .setNegativeButton(android.R.string.cancel, null)
} .create()
} }
companion object { companion object {

View file

@ -14,70 +14,60 @@
package code.name.monkey.retromusic.dialogs package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.Dialog import android.app.Dialog
import android.os.Bundle import android.os.Bundle
import android.provider.MediaStore import android.text.TextUtils
import android.widget.TextView import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.appthemehelper.util.MaterialUtil import code.name.monkey.appthemehelper.util.MaterialUtil
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.layout import code.name.monkey.retromusic.extensions.extraNotNull
import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.extensions.appHandleColor
import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.PlaylistsUtil import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textfield.TextInputLayout
class CreatePlaylistDialog : DialogFragment() { class CreatePlaylistDialog : DialogFragment() {
private lateinit var playlistView: TextInputEditText @SuppressLint("InflateParams")
private lateinit var actionNewPlaylistContainer: TextInputLayout
override fun onCreateDialog( override fun onCreateDialog(
savedInstanceState: Bundle? savedInstanceState: Bundle?
): Dialog { ): Dialog {
val materialDialog = MaterialDialog(requireContext()) val view = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_playlist, null)
.show { val playlistView: TextInputEditText = view.findViewById(R.id.actionNewPlaylist)
val playlistContainer: TextInputLayout = view.findViewById(R.id.actionNewPlaylistContainer)
MaterialUtil.setTint(playlistContainer, false)
title(string.new_playlist_title) return MaterialAlertDialogBuilder(requireActivity(),
customView(layout.dialog_playlist) R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
negativeButton(android.R.string.cancel) .setTitle(R.string.new_playlist_title)
positiveButton(string.create_action) { .setView(view)
if (activity == null) { .setNegativeButton(android.R.string.cancel, null)
return@positiveButton .setPositiveButton(
} R.string.create_action
val songs = requireArguments().getParcelableArrayList<Song>("songs") ) { _, _ ->
?: return@positiveButton val extra = extraNotNull<ArrayList<Song>>("songs")
val playlistName = playlistView.text.toString()
if (playlistView.text.toString().trim { it <= ' ' }.isNotEmpty()) { if (!TextUtils.isEmpty(playlistName)) {
val playlistId = PlaylistsUtil.createPlaylist( val playlistId = PlaylistsUtil.createPlaylist(
requireContext(), requireContext(),
playlistView.text.toString() playlistView.text.toString()
) )
if (playlistId != -1) { if (playlistId != -1) {
PlaylistsUtil.addToPlaylist(requireContext(), songs, playlistId, true) PlaylistsUtil.addToPlaylist(requireContext(), extra.value, playlistId, true)
} }
} }
} }
.create()
} }
val dialogView = materialDialog.getCustomView() override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
playlistView = dialogView.findViewById(R.id.actionNewPlaylist) super.onViewCreated(view, savedInstanceState)
actionNewPlaylistContainer = dialogView.findViewById(R.id.actionNewPlaylistContainer) (dialog as AlertDialog)
MaterialUtil.setTint(actionNewPlaylistContainer, false)
val playlistId = requireArguments().getLong(MediaStore.Audio.Playlists.Members.PLAYLIST_ID)
playlistView.appHandleColor()
.setText(
PlaylistsUtil.getNameForPlaylist(requireContext(), playlistId),
TextView.BufferType.EDITABLE
)
return materialDialog
} }
companion object { companion object {

View file

@ -19,10 +19,9 @@ import android.os.Bundle
import androidx.core.text.HtmlCompat import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.model.Playlist import code.name.monkey.retromusic.model.Playlist
import code.name.monkey.retromusic.util.PlaylistsUtil import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import java.util.* import java.util.*
class DeletePlaylistDialog : DialogFragment() { class DeletePlaylistDialog : DialogFragment() {
@ -30,33 +29,33 @@ class DeletePlaylistDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val playlists = requireArguments().getParcelableArrayList<Playlist>("playlist") val playlists = requireArguments().getParcelableArrayList<Playlist>("playlist")
val title: Int val title: Int
val content: CharSequence val message: CharSequence
//noinspection ConstantConditions //noinspection ConstantConditions
if (playlists!!.size > 1) { if (playlists!!.size > 1) {
title = string.delete_playlists_title title = R.string.delete_playlists_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString(string.delete_x_playlists, playlists.size), getString(R.string.delete_x_playlists, playlists.size),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
} else { } else {
title = string.delete_playlist_title title = R.string.delete_playlist_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString(string.delete_playlist_x, playlists[0].name), getString(R.string.delete_playlist_x, playlists[0].name),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
} }
return MaterialDialog(requireContext()) return MaterialAlertDialogBuilder(
.show { requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
title(title) )
message(text = content) .setTitle(title)
negativeButton(android.R.string.cancel) .setMessage(message)
positiveButton(R.string.action_delete) { .setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_delete) { _, _ ->
PlaylistsUtil.deletePlaylists(requireContext(), playlists) PlaylistsUtil.deletePlaylists(requireContext(), playlists)
} }
negativeButton(android.R.string.cancel) .create()
}
} }
companion object { companion object {

View file

@ -55,7 +55,8 @@ public class DeleteSongsAsyncTask extends DialogAsyncTask<DeleteSongsAsyncTask.L
@NonNull @NonNull
@Override @Override
protected Dialog createDialog(@NonNull Context context) { protected Dialog createDialog(@NonNull Context context) {
return new MaterialAlertDialogBuilder(context) return new MaterialAlertDialogBuilder(context,
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(R.string.deleting_songs) .setTitle(R.string.deleting_songs)
.setView(R.layout.loading) .setView(R.layout.loading)
.setCancelable(false) .setCancelable(false)

View file

@ -22,11 +22,12 @@ import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.activities.saf.SAFGuideActivity import code.name.monkey.retromusic.activities.saf.SAFGuideActivity
import code.name.monkey.retromusic.extensions.extraNotNull
import code.name.monkey.retromusic.helper.MusicPlayerRemote import code.name.monkey.retromusic.helper.MusicPlayerRemote
import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.MusicUtil import code.name.monkey.retromusic.util.MusicUtil
import code.name.monkey.retromusic.util.SAFUtil import code.name.monkey.retromusic.util.SAFUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
class DeleteSongsDialog : DialogFragment() { class DeleteSongsDialog : DialogFragment() {
@JvmField @JvmField
@ -38,45 +39,38 @@ class DeleteSongsDialog : DialogFragment() {
private var deleteSongsAsyncTask: DeleteSongsAsyncTask? = null private var deleteSongsAsyncTask: DeleteSongsAsyncTask? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val songs: ArrayList<Song>? = requireArguments().getParcelableArrayList("songs") val songs = extraNotNull<List<Song>>("songs¬").value
var title = 0 var title = 0
var content: CharSequence = "" var message: CharSequence = ""
if (songs != null) {
if (songs.size > 1) { if (songs.size > 1) {
title = R.string.delete_songs_title title = R.string.delete_songs_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString(R.string.delete_x_songs, songs.size), getString(R.string.delete_x_songs, songs.size),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
} else { } else {
title = R.string.delete_song_title title = R.string.delete_song_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString(R.string.delete_song_x, songs[0].title), getString(R.string.delete_song_x, songs[0].title),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
} }
}
return MaterialDialog(requireContext()).show { return MaterialAlertDialogBuilder(requireContext(),
title(title) R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
message(text = content) .setTitle(title)
negativeButton(android.R.string.cancel) { .setMessage(message)
dismiss() .setCancelable(false)
} .setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_delete) { _, _ ->
noAutoDismiss()
positiveButton(R.string.action_delete) {
if (songs != null) {
if ((songs.size == 1) && MusicPlayerRemote.isPlaying(songs[0])) { if ((songs.size == 1) && MusicPlayerRemote.isPlaying(songs[0])) {
MusicPlayerRemote.playNextSong() MusicPlayerRemote.playNextSong()
} }
}
songsToRemove = songs songsToRemove = songs
deleteSongsAsyncTask = DeleteSongsAsyncTask(this@DeleteSongsDialog) deleteSongsAsyncTask = DeleteSongsAsyncTask(this@DeleteSongsDialog)
deleteSongsAsyncTask?.execute(DeleteSongsAsyncTask.LoadingInfo(songs, null)) deleteSongsAsyncTask?.execute(DeleteSongsAsyncTask.LoadingInfo(songs, null))
} }
} .create()
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

View file

@ -22,7 +22,7 @@ import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.string import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.model.PlaylistSong import code.name.monkey.retromusic.model.PlaylistSong
import code.name.monkey.retromusic.util.PlaylistsUtil import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
class RemoveFromPlaylistDialog : DialogFragment() { class RemoveFromPlaylistDialog : DialogFragment() {
@ -30,17 +30,17 @@ class RemoveFromPlaylistDialog : DialogFragment() {
val songs = requireArguments().getParcelableArrayList<PlaylistSong>("songs") val songs = requireArguments().getParcelableArrayList<PlaylistSong>("songs")
var title = 0 var title = 0
var content: CharSequence = "" var message: CharSequence = ""
if (songs != null) { if (songs != null) {
if (songs.size > 1) { if (songs.size > 1) {
title = R.string.remove_songs_from_playlist_title title = R.string.remove_songs_from_playlist_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString(string.remove_x_songs_from_playlist, songs.size), getString(string.remove_x_songs_from_playlist, songs.size),
HtmlCompat.FROM_HTML_MODE_LEGACY HtmlCompat.FROM_HTML_MODE_LEGACY
) )
} else { } else {
title = R.string.remove_song_from_playlist_title title = R.string.remove_song_from_playlist_title
content = HtmlCompat.fromHtml( message = HtmlCompat.fromHtml(
getString( getString(
code.name.monkey.retromusic.R.string.remove_song_x_from_playlist, code.name.monkey.retromusic.R.string.remove_song_x_from_playlist,
songs[0].title songs[0].title
@ -50,22 +50,18 @@ class RemoveFromPlaylistDialog : DialogFragment() {
} }
} }
return MaterialAlertDialogBuilder(requireContext(),
return MaterialDialog(requireContext()) R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.show { .setTitle(title)
title(title) .setMessage(message)
message(text = content) .setPositiveButton(R.string.remove_action) { _, _ ->
negativeButton(android.R.string.cancel)
positiveButton(R.string.remove_action) {
if (activity == null)
return@positiveButton
PlaylistsUtil.removeFromPlaylist( PlaylistsUtil.removeFromPlaylist(
requireContext(), requireContext(),
songs as MutableList<PlaylistSong> songs as MutableList<PlaylistSong>
) )
} }
.setNegativeButton(android.R.string.cancel, null)
} .create()
} }
companion object { companion object {

View file

@ -14,59 +14,50 @@
package code.name.monkey.retromusic.dialogs package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.Dialog import android.app.Dialog
import android.os.Bundle import android.os.Bundle
import android.provider.MediaStore.Audio.Playlists.Members.PLAYLIST_ID import android.provider.MediaStore.Audio.Playlists.Members.PLAYLIST_ID
import android.widget.TextView import android.view.LayoutInflater
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.appthemehelper.util.MaterialUtil import code.name.monkey.appthemehelper.util.MaterialUtil
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.layout import code.name.monkey.retromusic.extensions.extraNotNull
import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.extensions.appHandleColor
import code.name.monkey.retromusic.util.PlaylistsUtil import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textfield.TextInputLayout
class RenamePlaylistDialog : DialogFragment() { class RenamePlaylistDialog : DialogFragment() {
private lateinit var playlistView: TextInputEditText
private lateinit var actionNewPlaylistContainer: TextInputLayout
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val materialDialog = MaterialDialog(requireContext())
.show {
title(string.rename_playlist_title) @SuppressLint("InflateParams")
customView(layout.dialog_playlist) override fun onCreateDialog(
negativeButton(android.R.string.cancel) savedInstanceState: Bundle?
positiveButton(string.action_rename) { ): Dialog {
if (playlistView.toString().trim { it <= ' ' } != "") { val layout = LayoutInflater.from(requireContext())
val playlistId = requireArguments().getLong(PLAYLIST_ID) .inflate(R.layout.dialog_playlist, null)
val inputEditText: TextInputEditText = layout.findViewById(R.id.actionNewPlaylist)
val nameContainer: TextInputLayout =
layout.findViewById(R.id.actionNewPlaylistContainer)
MaterialUtil.setTint(nameContainer, false)
return MaterialAlertDialogBuilder(requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(R.string.rename_playlist_title)
.setView(layout)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_rename) { _, _ ->
val name = inputEditText.text.toString()
if (name.isNotEmpty()) {
PlaylistsUtil.renamePlaylist( PlaylistsUtil.renamePlaylist(
context, requireContext(),
playlistId, extraNotNull<Long>(PLAYLIST_ID).value,
playlistView.text!!.toString() name
) )
} }
} }
} .create()
val dialogView = materialDialog.getCustomView()
playlistView = dialogView.findViewById(R.id.actionNewPlaylist)
actionNewPlaylistContainer = dialogView.findViewById(R.id.actionNewPlaylistContainer)
MaterialUtil.setTint(actionNewPlaylistContainer, false)
val playlistId = requireArguments().getLong(PLAYLIST_ID)
playlistView.appHandleColor()
.setText(
PlaylistsUtil.getNameForPlaylist(requireContext(), playlistId),
TextView.BufferType.EDITABLE
)
return materialDialog
} }
companion object { companion object {

View file

@ -14,6 +14,7 @@
package code.name.monkey.retromusic.dialogs package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.AlarmManager import android.app.AlarmManager
import android.app.Dialog import android.app.Dialog
import android.app.PendingIntent import android.app.PendingIntent
@ -22,28 +23,25 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.CountDownTimer import android.os.CountDownTimer
import android.os.SystemClock import android.os.SystemClock
import android.view.LayoutInflater
import android.widget.CheckBox import android.widget.CheckBox
import android.widget.SeekBar import android.widget.SeekBar
import android.widget.TextView import android.widget.TextView
import android.widget.Toast import android.widget.Toast
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.appthemehelper.ThemeStore
import code.name.monkey.appthemehelper.util.TintHelper
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.extensions.addAccentColor
import code.name.monkey.retromusic.helper.MusicPlayerRemote import code.name.monkey.retromusic.helper.MusicPlayerRemote
import code.name.monkey.retromusic.service.MusicService import code.name.monkey.retromusic.service.MusicService
import code.name.monkey.retromusic.service.MusicService.ACTION_PENDING_QUIT import code.name.monkey.retromusic.service.MusicService.ACTION_PENDING_QUIT
import code.name.monkey.retromusic.service.MusicService.ACTION_QUIT import code.name.monkey.retromusic.service.MusicService.ACTION_QUIT
import code.name.monkey.retromusic.util.MusicUtil import code.name.monkey.retromusic.util.MusicUtil
import code.name.monkey.retromusic.util.PreferenceUtilKT import code.name.monkey.retromusic.util.PreferenceUtilKT
import code.name.monkey.retromusic.util.ViewUtil import code.name.monkey.retromusic.util.ViewUtil
import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.actions.getActionButton
import com.afollestad.materialdialogs.callbacks.onShow import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
class SleepTimerDialog : DialogFragment() { class SleepTimerDialog : DialogFragment() {
@ -54,85 +52,26 @@ class SleepTimerDialog : DialogFragment() {
private lateinit var seekBar: SeekBar private lateinit var seekBar: SeekBar
private lateinit var timerDisplay: TextView private lateinit var timerDisplay: TextView
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
timerUpdater = TimerUpdater() timerUpdater = TimerUpdater()
val layout = LayoutInflater.from(requireContext())
materialDialog = MaterialDialog(requireContext()) .inflate(R.layout.dialog_sleep_timer, null)
.title(R.string.action_sleep_timer) shouldFinishLastSong = layout.findViewById(R.id.shouldFinishLastSong)
.positiveButton(R.string.action_set) { seekBar = layout.findViewById(R.id.seekBar)
PreferenceUtilKT.isSleepTimerFinishMusic = shouldFinishLastSong.isChecked timerDisplay = layout.findViewById(R.id.timerDisplay)
val minutes = seekArcProgress
val pi = makeTimerPendingIntent(PendingIntent.FLAG_CANCEL_CURRENT)
val nextSleepTimerElapsedTime = SystemClock.elapsedRealtime() + minutes * 60 * 1000
PreferenceUtilKT.nextSleepTimerElapsedRealTime = nextSleepTimerElapsedTime.toInt()
val am = requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextSleepTimerElapsedTime, pi)
Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_set, minutes),
Toast.LENGTH_SHORT
).show()
}
.negativeButton(android.R.string.cancel) {
if (activity == null) {
return@negativeButton
}
val previous = makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE)
if (previous != null) {
val am =
requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.cancel(previous)
previous.cancel()
Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_canceled),
Toast.LENGTH_SHORT
).show()
}
val musicService = MusicPlayerRemote.musicService
if (musicService != null && musicService.pendingQuit) {
musicService.pendingQuit = false
Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_canceled),
Toast.LENGTH_SHORT
).show()
}
}
.customView(R.layout.dialog_sleep_timer, scrollable = false)
.show {
onShow {
if (makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE) != null) {
timerUpdater.start()
}
}
}
if (activity == null || materialDialog.getCustomView() == null) {
return materialDialog
}
shouldFinishLastSong =
materialDialog.getCustomView().findViewById(R.id.shouldFinishLastSong)
seekBar = materialDialog.getCustomView().findViewById(R.id.seekBar)
timerDisplay = materialDialog.getCustomView().findViewById(R.id.timerDisplay)
TintHelper.setTintAuto(
shouldFinishLastSong,
ThemeStore.accentColor(requireContext()),
false
)
val finishMusic = PreferenceUtilKT.isSleepTimerFinishMusic val finishMusic = PreferenceUtilKT.isSleepTimerFinishMusic
shouldFinishLastSong.isChecked = finishMusic shouldFinishLastSong.apply {
addAccentColor()
isChecked = finishMusic
}
seekBar.apply {
addAccentColor()
seekArcProgress = PreferenceUtilKT.lastSleepTimerValue seekArcProgress = PreferenceUtilKT.lastSleepTimerValue
updateTimeDisplayTime() updateTimeDisplayTime()
seekBar.progress = seekArcProgress seekBar.progress = seekArcProgress
}
setProgressBarColor(ThemeStore.accentColor(requireContext()))
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
@ -151,8 +90,51 @@ class SleepTimerDialog : DialogFragment() {
PreferenceUtilKT.lastSleepTimerValue = seekArcProgress PreferenceUtilKT.lastSleepTimerValue = seekArcProgress
} }
}) })
return MaterialAlertDialogBuilder(
requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
)
.setTitle(R.string.action_sleep_timer)
.setView(layout)
.setPositiveButton(R.string.action_set) { _, _ ->
PreferenceUtilKT.isSleepTimerFinishMusic = shouldFinishLastSong.isChecked
val minutes = seekArcProgress
val pi = makeTimerPendingIntent(PendingIntent.FLAG_CANCEL_CURRENT)
val nextSleepTimerElapsedTime = SystemClock.elapsedRealtime() + minutes * 60 * 1000
PreferenceUtilKT.nextSleepTimerElapsedRealTime = nextSleepTimerElapsedTime.toInt()
val am = requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextSleepTimerElapsedTime, pi)
return materialDialog Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_set, minutes),
Toast.LENGTH_SHORT
).show()
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
val previous = makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE)
if (previous != null) {
val am =
requireContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.cancel(previous)
previous.cancel()
Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_canceled),
Toast.LENGTH_SHORT
).show()
val musicService = MusicPlayerRemote.musicService
if (musicService != null && musicService.pendingQuit) {
musicService.pendingQuit = false
Toast.makeText(
requireContext(),
requireContext().resources.getString(R.string.sleep_timer_canceled),
Toast.LENGTH_SHORT
).show()
}
}
}
.create()
} }
private fun updateTimeDisplayTime() { private fun updateTimeDisplayTime() {

View file

@ -14,11 +14,13 @@
package code.name.monkey.retromusic.dialogs package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.Dialog import android.app.Dialog
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.text.Spanned import android.text.Spanned
import android.util.Log import android.util.Log
import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.TextView import android.widget.TextView
@ -26,12 +28,9 @@ import androidx.annotation.NonNull
import androidx.core.text.HtmlCompat import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.MusicUtil import code.name.monkey.retromusic.util.MusicUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import org.jaudiotagger.audio.AudioFileIO import org.jaudiotagger.audio.AudioFileIO
import org.jaudiotagger.audio.exceptions.CannotReadException import org.jaudiotagger.audio.exceptions.CannotReadException
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
@ -48,22 +47,12 @@ inline fun ViewGroup.forEach(action: (View) -> Unit) {
class SongDetailDialog : DialogFragment() { class SongDetailDialog : DialogFragment() {
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context: Context = requireContext() val context: Context = requireContext()
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_file_details, null)
val song = requireArguments().getParcelable<Song>("song") val song = requireArguments().getParcelable<Song>("song")
val materialDialog = MaterialDialog(requireContext())
.show {
customView(
R.layout.dialog_file_details,
scrollable = true
)
positiveButton(android.R.string.ok)
title(string.action_details)
}
val dialogView = materialDialog.getCustomView()
val fileName: TextView = dialogView.findViewById(R.id.fileName) val fileName: TextView = dialogView.findViewById(R.id.fileName)
val filePath: TextView = dialogView.findViewById(R.id.filePath) val filePath: TextView = dialogView.findViewById(R.id.filePath)
val fileSize: TextView = dialogView.findViewById(R.id.fileSize) val fileSize: TextView = dialogView.findViewById(R.id.fileSize)
@ -72,23 +61,23 @@ class SongDetailDialog : DialogFragment() {
val bitRate: TextView = dialogView.findViewById(R.id.bitrate) val bitRate: TextView = dialogView.findViewById(R.id.bitrate)
val samplingRate: TextView = dialogView.findViewById(R.id.samplingRate) val samplingRate: TextView = dialogView.findViewById(R.id.samplingRate)
fileName.text = makeTextWithTitle(context, string.label_file_name, "-") fileName.text = makeTextWithTitle(context, R.string.label_file_name, "-")
filePath.text = makeTextWithTitle(context, string.label_file_path, "-") filePath.text = makeTextWithTitle(context, R.string.label_file_path, "-")
fileSize.text = makeTextWithTitle(context, string.label_file_size, "-") fileSize.text = makeTextWithTitle(context, R.string.label_file_size, "-")
fileFormat.text = makeTextWithTitle(context, string.label_file_format, "-") fileFormat.text = makeTextWithTitle(context, R.string.label_file_format, "-")
trackLength.text = makeTextWithTitle(context, string.label_track_length, "-") trackLength.text = makeTextWithTitle(context, R.string.label_track_length, "-")
bitRate.text = makeTextWithTitle(context, string.label_bit_rate, "-") bitRate.text = makeTextWithTitle(context, R.string.label_bit_rate, "-")
samplingRate.text = makeTextWithTitle(context, string.label_sampling_rate, "-") samplingRate.text = makeTextWithTitle(context, R.string.label_sampling_rate, "-")
if (song != null) { if (song != null) {
val songFile = File(song.data) val songFile = File(song.data)
if (songFile.exists()) { if (songFile.exists()) {
fileName.text = makeTextWithTitle(context, string.label_file_name, songFile.name) fileName.text = makeTextWithTitle(context, R.string.label_file_name, songFile.name)
filePath.text = filePath.text =
makeTextWithTitle(context, string.label_file_path, songFile.absolutePath) makeTextWithTitle(context, R.string.label_file_path, songFile.absolutePath)
fileSize.text = fileSize.text =
makeTextWithTitle( makeTextWithTitle(
context, context,
string.label_file_size, R.string.label_file_size,
getFileSizeString(songFile.length()) getFileSizeString(songFile.length())
) )
try { try {
@ -96,21 +85,21 @@ class SongDetailDialog : DialogFragment() {
val audioHeader = audioFile.audioHeader val audioHeader = audioFile.audioHeader
fileFormat.text = fileFormat.text =
makeTextWithTitle(context, string.label_file_format, audioHeader.format) makeTextWithTitle(context, R.string.label_file_format, audioHeader.format)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString((audioHeader.trackLength * 1000).toLong()) MusicUtil.getReadableDurationString((audioHeader.trackLength * 1000).toLong())
) )
bitRate.text = makeTextWithTitle( bitRate.text = makeTextWithTitle(
context, context,
string.label_bit_rate, R.string.label_bit_rate,
audioHeader.bitRate + " kb/s" audioHeader.bitRate + " kb/s"
) )
samplingRate.text = samplingRate.text =
makeTextWithTitle( makeTextWithTitle(
context, context,
string.label_sampling_rate, R.string.label_sampling_rate,
audioHeader.sampleRate + " Hz" audioHeader.sampleRate + " Hz"
) )
} catch (@NonNull e: CannotReadException) { } catch (@NonNull e: CannotReadException) {
@ -118,50 +107,55 @@ class SongDetailDialog : DialogFragment() {
// fallback // fallback
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} catch (@NonNull e: IOException) { } catch (@NonNull e: IOException) {
Log.e(TAG, "error while reading the song file", e) Log.e(TAG, "error while reading the song file", e)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} catch (@NonNull e: TagException) { } catch (@NonNull e: TagException) {
Log.e(TAG, "error while reading the song file", e) Log.e(TAG, "error while reading the song file", e)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} catch (@NonNull e: ReadOnlyFileException) { } catch (@NonNull e: ReadOnlyFileException) {
Log.e(TAG, "error while reading the song file", e) Log.e(TAG, "error while reading the song file", e)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} catch (@NonNull e: InvalidAudioFrameException) { } catch (@NonNull e: InvalidAudioFrameException) {
Log.e(TAG, "error while reading the song file", e) Log.e(TAG, "error while reading the song file", e)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} }
} else { } else {
// fallback // fallback
fileName.text = makeTextWithTitle(context, string.label_file_name, song.title) fileName.text = makeTextWithTitle(context, R.string.label_file_name, song.title)
trackLength.text = makeTextWithTitle( trackLength.text = makeTextWithTitle(
context, context,
string.label_track_length, R.string.label_track_length,
MusicUtil.getReadableDurationString(song.duration) MusicUtil.getReadableDurationString(song.duration)
) )
} }
} }
return MaterialAlertDialogBuilder(
return materialDialog requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
).setTitle(R.string.action_details)
.setPositiveButton(android.R.string.ok, null)
.setView(dialogView)
.create()
} }
companion object { companion object {

View file

@ -22,32 +22,41 @@ import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.activities.ShareInstagramStory import code.name.monkey.retromusic.activities.ShareInstagramStory
import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.MusicUtil import code.name.monkey.retromusic.util.MusicUtil
import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.afollestad.materialdialogs.list.listItems
class SongShareDialog : DialogFragment() { class SongShareDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val song: Song? = requireArguments().getParcelable("song") val song: Song? = requireArguments().getParcelable("song")
val currentlyListening: String = val listening: String =
getString(R.string.currently_listening_to_x_by_x, song?.title, song?.artistName) getString(R.string.currently_listening_to_x_by_x, song?.title, song?.artistName)
return MaterialDialog(requireContext()) return MaterialAlertDialogBuilder(
.title(R.string.what_do_you_want_to_share) requireContext(),
.show { R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
).setTitle(R.string.what_do_you_want_to_share)
listItems( .setItems(
items = listOf( arrayOf(
getString(code.name.monkey.retromusic.R.string.the_audio_file), getString(R.string.the_audio_file),
"\u201C" + currentlyListening + "\u201D", "\u201C" + listening + "\u201D",
getString(R.string.social_stories) getString(R.string.social_stories)
) )
) { _, index, _ -> ) { _, which ->
when (index) { withAction(which, song, listening)
}
.create()
}
private fun withAction(
which: Int,
song: Song?,
currentlyListening: String
) {
when (which) {
0 -> { 0 -> {
startActivity(Intent.createChooser(song?.let { startActivity(Intent.createChooser(song?.let {
MusicUtil.createShareSongFileIntent( MusicUtil.createShareSongFileIntent(
it, it,
context requireContext()
) )
}, null)) }, null))
} }
@ -77,8 +86,6 @@ class SongShareDialog : DialogFragment() {
} }
} }
} }
}
}
companion object { companion object {

View file

@ -14,6 +14,7 @@
package code.name.monkey.retromusic.extensions package code.name.monkey.retromusic.extensions
import android.app.Activity
import androidx.annotation.IdRes import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
@ -63,3 +64,13 @@ fun AppCompatActivity.replaceFragment(
commit() commit()
} }
} }
inline fun <reified T : Any> Activity.extra(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
if (value is T) value else default
}
inline fun <reified T : Any> Activity.extraNotNull(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
requireNotNull(if (value is T) value else default) { key }
}

View file

@ -18,6 +18,8 @@ import android.app.Dialog
import android.content.Context import android.content.Context
import android.content.res.ColorStateList import android.content.res.ColorStateList
import android.graphics.Color import android.graphics.Color
import android.widget.CheckBox
import android.widget.SeekBar
import androidx.annotation.AttrRes import androidx.annotation.AttrRes
import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
@ -65,3 +67,14 @@ fun Fragment.resolveColor(@AttrRes attr: Int, fallBackColor: Int = 0) =
fun Dialog.resolveColor(@AttrRes attr: Int, fallBackColor: Int = 0) = fun Dialog.resolveColor(@AttrRes attr: Int, fallBackColor: Int = 0) =
ATHUtil.resolveColor(context, attr, fallBackColor) ATHUtil.resolveColor(context, attr, fallBackColor)
fun CheckBox.addAccentColor() {
buttonTintList = ColorStateList.valueOf(ThemeStore.accentColor(context))
}
fun SeekBar.addAccentColor() {
val colorState = ColorStateList.valueOf(ThemeStore.accentColor(context))
progressTintList = colorState
thumbTintList = colorState
}

View file

@ -26,3 +26,14 @@ fun Context.isSystemDarkModeEnabled(): Boolean {
(resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
return isBatterySaverEnabled or isDarkModeEnabled return isBatterySaverEnabled or isDarkModeEnabled
} }
inline fun <reified T : Any> Fragment.extra(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
if (value is T) value else default
}
inline fun <reified T : Any> Fragment.extraNotNull(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
requireNotNull(if (value is T) value else default) { key }
}

View file

@ -21,7 +21,7 @@ import code.name.monkey.retromusic.model.Artist
import code.name.monkey.retromusic.util.PreferenceUtilKT import code.name.monkey.retromusic.util.PreferenceUtilKT
object ArtistLoader { object ArtistLoader {
private fun getSongLoaderSortOrder(context: Context): String { private fun getSongLoaderSortOrder(): String {
return PreferenceUtilKT.artistSortOrder + ", " + return PreferenceUtilKT.artistSortOrder + ", " +
PreferenceUtilKT.artistAlbumSortOrder + ", " + PreferenceUtilKT.artistAlbumSortOrder + ", " +
PreferenceUtilKT.artistSongSortOrder PreferenceUtilKT.artistSongSortOrder
@ -32,7 +32,7 @@ object ArtistLoader {
SongLoader.makeSongCursor( SongLoader.makeSongCursor(
context, context,
null, null, null, null,
getSongLoaderSortOrder(context) getSongLoaderSortOrder()
) )
) )
return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs)) return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))
@ -44,7 +44,7 @@ object ArtistLoader {
context, context,
AudioColumns.ARTIST + " LIKE ?", AudioColumns.ARTIST + " LIKE ?",
arrayOf("%$query%"), arrayOf("%$query%"),
getSongLoaderSortOrder(context) getSongLoaderSortOrder()
) )
) )
return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs)) return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))
@ -78,7 +78,7 @@ object ArtistLoader {
context, context,
AudioColumns.ARTIST_ID + "=?", AudioColumns.ARTIST_ID + "=?",
arrayOf(artistId.toString()), arrayOf(artistId.toString()),
getSongLoaderSortOrder(context) getSongLoaderSortOrder()
) )
) )
return Artist(AlbumLoader.splitIntoAlbums(songs)) return Artist(AlbumLoader.splitIntoAlbums(songs))

View file

@ -80,15 +80,14 @@ object GenreLoader {
} }
private fun makeAllSongsWithGenreCursor(context: Context): Cursor? { private fun makeAllSongsWithGenreCursor(context: Context): Cursor? {
try { return try {
return context.contentResolver.query( context.contentResolver.query(
Uri.parse("content://media/external/audio/genres/all/members"), Uri.parse("content://media/external/audio/genres/all/members"),
arrayOf(Genres.Members.AUDIO_ID), null, null, null arrayOf(Genres.Members.AUDIO_ID), null, null, null
) )
} catch (e: SecurityException) { } catch (e: SecurityException) {
return null null
} }
} }
private fun makeGenreSongCursor(context: Context, genreId: Int): Cursor? { private fun makeGenreSongCursor(context: Context, genreId: Int): Cursor? {

View file

@ -79,7 +79,8 @@ class AlbumCoverStylePreferenceDialog : DialogFragment(),
viewPager.pageMargin = ViewUtil.convertDpToPixel(32f, resources).toInt() viewPager.pageMargin = ViewUtil.convertDpToPixel(32f, resources).toInt()
viewPager.currentItem = PreferenceUtilKT.albumCoverStyle.ordinal viewPager.currentItem = PreferenceUtilKT.albumCoverStyle.ordinal
return MaterialAlertDialogBuilder(requireActivity()) return MaterialAlertDialogBuilder(requireActivity(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(R.string.pref_title_album_cover_style) .setTitle(R.string.pref_title_album_cover_style)
.setPositiveButton(R.string.set) { _, _ -> .setPositiveButton(R.string.set) { _, _ ->
val coverStyle = values()[viewPagerPosition] val coverStyle = values()[viewPagerPosition]

View file

@ -19,9 +19,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:maxHeight="3dp" android:maxHeight="3dp"
android:paddingTop="12dp" android:paddingTop="12dp"
android:progressDrawable="@drawable/color_progress_seek"
android:splitTrack="false" android:splitTrack="false"
android:thumb="@drawable/switch_thumb_material"
tools:progress="20" /> tools:progress="20" />
<com.google.android.material.checkbox.MaterialCheckBox <com.google.android.material.checkbox.MaterialCheckBox

View file

@ -28,6 +28,8 @@ import androidx.preference.DialogPreference;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import code.name.monkey.appthemehelper.R;
/** /**
* @author Karim Abou Zeid (kabouzeid) * @author Karim Abou Zeid (kabouzeid)
*/ */
@ -63,7 +65,8 @@ public class ATEPreferenceDialogFragment extends DialogFragment {
@NonNull @NonNull
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
MaterialAlertDialogBuilder materialDialog = new MaterialAlertDialogBuilder(requireActivity()) MaterialAlertDialogBuilder materialDialog = new MaterialAlertDialogBuilder(requireActivity(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(mPreference.getTitle()) .setTitle(mPreference.getTitle())
.setIcon(mPreference.getIcon()) .setIcon(mPreference.getIcon())
.setMessage(mPreference.getDialogMessage()) .setMessage(mPreference.getDialogMessage())