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
}
override fun onCreate(savedInstanceState: Bundle?) {
setDrawUnderStatusBar()
super.onCreate(savedInstanceState)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -55,7 +55,8 @@ public class DeleteSongsAsyncTask extends DialogAsyncTask<DeleteSongsAsyncTask.L
@NonNull
@Override
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)
.setView(R.layout.loading)
.setCancelable(false)

View file

@ -22,11 +22,12 @@ import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment
import code.name.monkey.retromusic.R
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.model.Song
import code.name.monkey.retromusic.util.MusicUtil
import code.name.monkey.retromusic.util.SAFUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class DeleteSongsDialog : DialogFragment() {
@JvmField
@ -38,45 +39,38 @@ class DeleteSongsDialog : DialogFragment() {
private var deleteSongsAsyncTask: DeleteSongsAsyncTask? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val songs: ArrayList<Song>? = requireArguments().getParcelableArrayList("songs")
val songs = extraNotNull<List<Song>>("songs¬").value
var title = 0
var content: CharSequence = ""
if (songs != null) {
if (songs.size > 1) {
title = R.string.delete_songs_title
content = HtmlCompat.fromHtml(
getString(R.string.delete_x_songs, songs.size),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
} else {
title = R.string.delete_song_title
content = HtmlCompat.fromHtml(
getString(R.string.delete_song_x, songs[0].title),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
}
var message: CharSequence = ""
if (songs.size > 1) {
title = R.string.delete_songs_title
message = HtmlCompat.fromHtml(
getString(R.string.delete_x_songs, songs.size),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
} else {
title = R.string.delete_song_title
message = HtmlCompat.fromHtml(
getString(R.string.delete_song_x, songs[0].title),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
}
return MaterialDialog(requireContext()).show {
title(title)
message(text = content)
negativeButton(android.R.string.cancel) {
dismiss()
}
noAutoDismiss()
positiveButton(R.string.action_delete) {
if (songs != null) {
if ((songs.size == 1) && MusicPlayerRemote.isPlaying(songs[0])) {
MusicPlayerRemote.playNextSong()
}
return MaterialAlertDialogBuilder(requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_delete) { _, _ ->
if ((songs.size == 1) && MusicPlayerRemote.isPlaying(songs[0])) {
MusicPlayerRemote.playNextSong()
}
songsToRemove = songs
deleteSongsAsyncTask = DeleteSongsAsyncTask(this@DeleteSongsDialog)
deleteSongsAsyncTask?.execute(DeleteSongsAsyncTask.LoadingInfo(songs, null))
}
}
.create()
}
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.model.PlaylistSong
import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class RemoveFromPlaylistDialog : DialogFragment() {
@ -30,17 +30,17 @@ class RemoveFromPlaylistDialog : DialogFragment() {
val songs = requireArguments().getParcelableArrayList<PlaylistSong>("songs")
var title = 0
var content: CharSequence = ""
var message: CharSequence = ""
if (songs != null) {
if (songs.size > 1) {
title = R.string.remove_songs_from_playlist_title
content = HtmlCompat.fromHtml(
message = HtmlCompat.fromHtml(
getString(string.remove_x_songs_from_playlist, songs.size),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
} else {
title = R.string.remove_song_from_playlist_title
content = HtmlCompat.fromHtml(
message = HtmlCompat.fromHtml(
getString(
code.name.monkey.retromusic.R.string.remove_song_x_from_playlist,
songs[0].title
@ -50,22 +50,18 @@ class RemoveFromPlaylistDialog : DialogFragment() {
}
}
return MaterialDialog(requireContext())
.show {
title(title)
message(text = content)
negativeButton(android.R.string.cancel)
positiveButton(R.string.remove_action) {
if (activity == null)
return@positiveButton
PlaylistsUtil.removeFromPlaylist(
requireContext(),
songs as MutableList<PlaylistSong>
)
}
return MaterialAlertDialogBuilder(requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.remove_action) { _, _ ->
PlaylistsUtil.removeFromPlaylist(
requireContext(),
songs as MutableList<PlaylistSong>
)
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
companion object {

View file

@ -14,59 +14,50 @@
package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.provider.MediaStore.Audio.Playlists.Members.PLAYLIST_ID
import android.widget.TextView
import android.view.LayoutInflater
import androidx.fragment.app.DialogFragment
import code.name.monkey.appthemehelper.util.MaterialUtil
import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.R.layout
import code.name.monkey.retromusic.R.string
import code.name.monkey.retromusic.extensions.appHandleColor
import code.name.monkey.retromusic.extensions.extraNotNull
import code.name.monkey.retromusic.util.PlaylistsUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
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)
customView(layout.dialog_playlist)
negativeButton(android.R.string.cancel)
positiveButton(string.action_rename) {
if (playlistView.toString().trim { it <= ' ' } != "") {
val playlistId = requireArguments().getLong(PLAYLIST_ID)
PlaylistsUtil.renamePlaylist(
context,
playlistId,
playlistView.text!!.toString()
)
}
@SuppressLint("InflateParams")
override fun onCreateDialog(
savedInstanceState: Bundle?
): Dialog {
val layout = LayoutInflater.from(requireContext())
.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(
requireContext(),
extraNotNull<Long>(PLAYLIST_ID).value,
name
)
}
}
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
.create()
}
companion object {

View file

@ -14,6 +14,7 @@
package code.name.monkey.retromusic.dialogs
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.Dialog
import android.app.PendingIntent
@ -22,28 +23,25 @@ import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.os.SystemClock
import android.view.LayoutInflater
import android.widget.CheckBox
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
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.extensions.addAccentColor
import code.name.monkey.retromusic.helper.MusicPlayerRemote
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_QUIT
import code.name.monkey.retromusic.util.MusicUtil
import code.name.monkey.retromusic.util.PreferenceUtilKT
import code.name.monkey.retromusic.util.ViewUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.getActionButton
import com.afollestad.materialdialogs.callbacks.onShow
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class SleepTimerDialog : DialogFragment() {
@ -54,85 +52,26 @@ class SleepTimerDialog : DialogFragment() {
private lateinit var seekBar: SeekBar
private lateinit var timerDisplay: TextView
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
timerUpdater = TimerUpdater()
materialDialog = MaterialDialog(requireContext())
.title(R.string.action_sleep_timer)
.positiveButton(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)
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 layout = LayoutInflater.from(requireContext())
.inflate(R.layout.dialog_sleep_timer, null)
shouldFinishLastSong = layout.findViewById(R.id.shouldFinishLastSong)
seekBar = layout.findViewById(R.id.seekBar)
timerDisplay = layout.findViewById(R.id.timerDisplay)
val finishMusic = PreferenceUtilKT.isSleepTimerFinishMusic
shouldFinishLastSong.isChecked = finishMusic
seekArcProgress = PreferenceUtilKT.lastSleepTimerValue
updateTimeDisplayTime()
seekBar.progress = seekArcProgress
setProgressBarColor(ThemeStore.accentColor(requireContext()))
shouldFinishLastSong.apply {
addAccentColor()
isChecked = finishMusic
}
seekBar.apply {
addAccentColor()
seekArcProgress = PreferenceUtilKT.lastSleepTimerValue
updateTimeDisplayTime()
seekBar.progress = seekArcProgress
}
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
@ -151,8 +90,51 @@ class SleepTimerDialog : DialogFragment() {
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() {

View file

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

View file

@ -22,62 +22,69 @@ import code.name.monkey.retromusic.R
import code.name.monkey.retromusic.activities.ShareInstagramStory
import code.name.monkey.retromusic.model.Song
import code.name.monkey.retromusic.util.MusicUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class SongShareDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
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)
return MaterialDialog(requireContext())
.title(R.string.what_do_you_want_to_share)
.show {
return MaterialAlertDialogBuilder(
requireContext(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert
).setTitle(R.string.what_do_you_want_to_share)
.setItems(
arrayOf(
getString(R.string.the_audio_file),
"\u201C" + listening + "\u201D",
getString(R.string.social_stories)
)
) { _, which ->
withAction(which, song, listening)
}
.create()
}
listItems(
items = listOf(
getString(code.name.monkey.retromusic.R.string.the_audio_file),
"\u201C" + currentlyListening + "\u201D",
getString(R.string.social_stories)
private fun withAction(
which: Int,
song: Song?,
currentlyListening: String
) {
when (which) {
0 -> {
startActivity(Intent.createChooser(song?.let {
MusicUtil.createShareSongFileIntent(
it,
requireContext()
)
}, null))
}
1 -> {
startActivity(
Intent.createChooser(
Intent()
.setAction(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, currentlyListening)
.setType("text/plain"),
null
)
)
}
2 -> {
if (song != null) {
startActivity(
Intent(
requireContext(),
ShareInstagramStory::class.java
).putExtra(
ShareInstagramStory.EXTRA_SONG,
song
)
)
) { _, index, _ ->
when (index) {
0 -> {
startActivity(Intent.createChooser(song?.let {
MusicUtil.createShareSongFileIntent(
it,
context
)
}, null))
}
1 -> {
startActivity(
Intent.createChooser(
Intent()
.setAction(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, currentlyListening)
.setType("text/plain"),
null
)
)
}
2 -> {
if (song != null) {
startActivity(
Intent(
requireContext(),
ShareInstagramStory::class.java
).putExtra(
ShareInstagramStory.EXTRA_SONG,
song
)
)
}
}
}
}
}
}
}
companion object {

View file

@ -14,6 +14,7 @@
package code.name.monkey.retromusic.extensions
import android.app.Activity
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
@ -62,4 +63,14 @@ fun AppCompatActivity.replaceFragment(
}
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.res.ColorStateList
import android.graphics.Color
import android.widget.CheckBox
import android.widget.SeekBar
import androidx.annotation.AttrRes
import androidx.appcompat.widget.Toolbar
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) =
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
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
object ArtistLoader {
private fun getSongLoaderSortOrder(context: Context): String {
private fun getSongLoaderSortOrder(): String {
return PreferenceUtilKT.artistSortOrder + ", " +
PreferenceUtilKT.artistAlbumSortOrder + ", " +
PreferenceUtilKT.artistSongSortOrder
@ -32,7 +32,7 @@ object ArtistLoader {
SongLoader.makeSongCursor(
context,
null, null,
getSongLoaderSortOrder(context)
getSongLoaderSortOrder()
)
)
return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))
@ -44,7 +44,7 @@ object ArtistLoader {
context,
AudioColumns.ARTIST + " LIKE ?",
arrayOf("%$query%"),
getSongLoaderSortOrder(context)
getSongLoaderSortOrder()
)
)
return splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))
@ -78,7 +78,7 @@ object ArtistLoader {
context,
AudioColumns.ARTIST_ID + "=?",
arrayOf(artistId.toString()),
getSongLoaderSortOrder(context)
getSongLoaderSortOrder()
)
)
return Artist(AlbumLoader.splitIntoAlbums(songs))

View file

@ -80,15 +80,14 @@ object GenreLoader {
}
private fun makeAllSongsWithGenreCursor(context: Context): Cursor? {
try {
return context.contentResolver.query(
return try {
context.contentResolver.query(
Uri.parse("content://media/external/audio/genres/all/members"),
arrayOf(Genres.Members.AUDIO_ID), null, null, null
)
} catch (e: SecurityException) {
return null
null
}
}
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.currentItem = PreferenceUtilKT.albumCoverStyle.ordinal
return MaterialAlertDialogBuilder(requireActivity())
return MaterialAlertDialogBuilder(requireActivity(),
R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
.setTitle(R.string.pref_title_album_cover_style)
.setPositiveButton(R.string.set) { _, _ ->
val coverStyle = values()[viewPagerPosition]

View file

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

View file

@ -28,6 +28,8 @@ import androidx.preference.DialogPreference;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import code.name.monkey.appthemehelper.R;
/**
* @author Karim Abou Zeid (kabouzeid)
*/
@ -63,7 +65,8 @@ public class ATEPreferenceDialogFragment extends DialogFragment {
@NonNull
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())
.setIcon(mPreference.getIcon())
.setMessage(mPreference.getDialogMessage())