导入 v0.1.0 / v0.2.0 源码:五模块首版、交互重构、重复任务、任务分布
- 源码镜像 src/main(81 个文件):首页双模式、任务、项目、统计、设置 - 补齐 README / LICENSE / CHANGELOG / CONTRIBUTING / .gitignore - 不含构建配置、签名材料、编译产物与备份数据
This commit is contained in:
31
src/main/java/com/focusbox/app/App.kt
Normal file
31
src/main/java/com/focusbox/app/App.kt
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.focusbox.app
|
||||
|
||||
import android.app.Application
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.service.Notif
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.util.Prefs
|
||||
|
||||
class App : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Prefs.init(this)
|
||||
Store.init(this)
|
||||
Notif.createChannels(this)
|
||||
applyTheme()
|
||||
TimerCore.init(this)
|
||||
}
|
||||
|
||||
/** 深色模式在 Activity 创建前定好,避免首帧闪一下浅色再跳深色 */
|
||||
fun applyTheme() {
|
||||
AppCompatDelegate.setDefaultNightMode(
|
||||
when (Prefs.themeMode) {
|
||||
1 -> AppCompatDelegate.MODE_NIGHT_NO
|
||||
2 -> AppCompatDelegate.MODE_NIGHT_YES
|
||||
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
81
src/main/java/com/focusbox/app/model/Models.kt
Normal file
81
src/main/java/com/focusbox/app/model/Models.kt
Normal file
@@ -0,0 +1,81 @@
|
||||
package com.focusbox.app.model
|
||||
|
||||
/** 项目(清单)。收件箱固定 id=1,不可删除。 */
|
||||
data class Project(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val color: Int,
|
||||
val archived: Boolean,
|
||||
val sort: Int,
|
||||
val openTasks: Int,
|
||||
val doneTasks: Int,
|
||||
val focusSeconds: Int,
|
||||
val pomodoros: Int,
|
||||
) {
|
||||
val totalTasks: Int get() = openTasks + doneTasks
|
||||
val progress: Float get() = if (totalTasks == 0) 0f else doneTasks.toFloat() / totalTasks
|
||||
}
|
||||
|
||||
/** 重复规则。间隔数量存在 Task.repeatEvery 里,这里只定义单位。 */
|
||||
object Repeat {
|
||||
const val NONE = 0
|
||||
const val DAY = 1
|
||||
const val WEEK = 2
|
||||
const val MONTH = 3
|
||||
}
|
||||
|
||||
data class Task(
|
||||
val id: Long,
|
||||
val title: String,
|
||||
val note: String,
|
||||
val projectId: Long,
|
||||
val priority: Int, // 0 低 / 1 中 / 2 高
|
||||
val focusMinutes: Int, // 单轮专注时长,选中任务后圆环直接用这个值
|
||||
val donePomodoros: Int,
|
||||
val due: Long, // 0 表示不设
|
||||
val done: Boolean,
|
||||
val doneAt: Long,
|
||||
val createdAt: Long,
|
||||
val sort: Int,
|
||||
val repeatType: Int, // Repeat.NONE / DAY / WEEK / MONTH
|
||||
val repeatEvery: Int, // 每 N 天 / 周 / 月
|
||||
) {
|
||||
val repeating: Boolean get() = repeatType != Repeat.NONE && repeatEvery > 0
|
||||
}
|
||||
|
||||
/** 一条专注记录的起止时刻,用于在已完成任务上显示实际工作时段。 */
|
||||
data class SessionSpan(val startAt: Long, val endAt: Long)
|
||||
|
||||
data class DayPoint(
|
||||
val key: String, // yyyy-MM-dd
|
||||
val label: String, // 坐标轴短标签
|
||||
val minutes: Int,
|
||||
val pomodoros: Int,
|
||||
)
|
||||
|
||||
/** 占比环的一片:项目分布与任务分布共用同一结构,避免两套绘制代码。 */
|
||||
data class ProjectSlice(
|
||||
val projectId: Long,
|
||||
val name: String,
|
||||
val color: Int,
|
||||
val seconds: Int,
|
||||
val pomodoros: Int,
|
||||
)
|
||||
|
||||
data class Totals(
|
||||
val seconds: Int = 0,
|
||||
val pomodoros: Int = 0,
|
||||
val doneTasks: Int = 0,
|
||||
val streak: Int = 0,
|
||||
)
|
||||
|
||||
/** 统计页顶部"今日"卡片的一次性数据 */
|
||||
data class TodayStat(
|
||||
val minutes: Int = 0,
|
||||
val pomodoros: Int = 0,
|
||||
val doneTasks: Int = 0,
|
||||
val goalMinutes: Int = 120,
|
||||
) {
|
||||
val goalProgress: Float
|
||||
get() = if (goalMinutes <= 0) 0f else (minutes.toFloat() / goalMinutes).coerceIn(0f, 1f)
|
||||
}
|
||||
167
src/main/java/com/focusbox/app/service/Notif.kt
Normal file
167
src/main/java/com/focusbox/app/service/Notif.kt
Normal file
@@ -0,0 +1,167 @@
|
||||
package com.focusbox.app.service
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.ui.MainActivity
|
||||
import com.focusbox.app.util.Dates
|
||||
|
||||
/**
|
||||
* 通知构建集中在这里:常驻计时通知 + 结束提醒,两条通道用途不同。
|
||||
*
|
||||
* 常驻通知的时间交给系统 Chronometer 渲染,而不是每秒重发一条通知:
|
||||
* 锁屏与息屏时第三方进程常被限流,自己刷新文本会"冻住",
|
||||
* 系统级计时器的走时不受这个限制。
|
||||
*/
|
||||
object Notif {
|
||||
|
||||
const val CHANNEL_TIMER = "timer_ongoing"
|
||||
const val CHANNEL_ALERT = "timer_alert"
|
||||
|
||||
const val ID_ONGOING = 1001
|
||||
private const val ID_ALERT = 1002
|
||||
|
||||
fun createChannels(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
|
||||
val ongoing = NotificationChannel(
|
||||
CHANNEL_TIMER,
|
||||
context.getString(R.string.notif_channel),
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = context.getString(R.string.notif_channel_desc)
|
||||
setShowBadge(false)
|
||||
enableVibration(false)
|
||||
setSound(null, null)
|
||||
}
|
||||
nm.createNotificationChannel(ongoing)
|
||||
|
||||
// 提醒通道交给我们自己播放声音与振动,这里保持静默,避免"响两遍"。
|
||||
val alert = NotificationChannel(
|
||||
CHANNEL_ALERT,
|
||||
"计时结束提醒",
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
enableVibration(false)
|
||||
setSound(null, null)
|
||||
setShowBadge(true)
|
||||
}
|
||||
nm.createNotificationChannel(alert)
|
||||
}
|
||||
|
||||
private fun contentIntent(context: Context): PendingIntent {
|
||||
val i = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
putExtra(MainActivity.EXTRA_TAB, MainActivity.TAB_FOCUS)
|
||||
}
|
||||
return PendingIntent.getActivity(
|
||||
context, 0, i,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun serviceAction(context: Context, action: String, requestCode: Int): PendingIntent {
|
||||
val i = Intent(context, TimerService::class.java).setAction(action)
|
||||
return PendingIntent.getService(
|
||||
context, requestCode, i,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
}
|
||||
|
||||
fun buildOngoing(context: Context): Notification {
|
||||
val running = TimerCore.running
|
||||
val countUp = TimerCore.countUp
|
||||
val taskName = if (TimerCore.taskId > 0) {
|
||||
com.focusbox.app.data.Store.task(TimerCore.taskId)?.title
|
||||
} else null
|
||||
|
||||
val b = NotificationCompat.Builder(context, CHANNEL_TIMER)
|
||||
// 透明小图标:状态栏与通知左侧不再出现应用图标
|
||||
.setSmallIcon(R.drawable.ic_notif_blank)
|
||||
.setContentIntent(contentIntent(context))
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setSilent(true)
|
||||
|
||||
if (running) {
|
||||
b.setUsesChronometer(true)
|
||||
if (countUp) {
|
||||
// 正计时:系统计时器从"已用时"往前推起点,界面上就是一直往上走
|
||||
b.setWhen(System.currentTimeMillis() - TimerCore.displayNow())
|
||||
b.setChronometerCountDown(false)
|
||||
} else {
|
||||
// 倒计时:渲染到结束时刻,系统自己一秒一秒减
|
||||
b.setWhen(TimerCore.endAtMs())
|
||||
b.setChronometerCountDown(true)
|
||||
}
|
||||
// 不再出现"专注中/休息中"字样,标题只留任务名(无任务则空白)
|
||||
b.setContentTitle(taskName ?: " ")
|
||||
} else {
|
||||
b.setShowWhen(false)
|
||||
b.setContentTitle(Dates.clock(TimerCore.displayNow()))
|
||||
b.setContentText(taskName ?: "")
|
||||
}
|
||||
|
||||
val toggleIcon = if (running) R.drawable.ic_pause else R.drawable.ic_play
|
||||
b.addAction(
|
||||
NotificationCompat.Action(
|
||||
toggleIcon, "",
|
||||
serviceAction(
|
||||
context,
|
||||
if (running) TimerService.ACTION_PAUSE else TimerService.ACTION_RESUME,
|
||||
11,
|
||||
),
|
||||
)
|
||||
)
|
||||
b.addAction(
|
||||
NotificationCompat.Action(
|
||||
R.drawable.ic_stop, "",
|
||||
serviceAction(context, TimerService.ACTION_STOP, 13),
|
||||
)
|
||||
)
|
||||
return b.build()
|
||||
}
|
||||
|
||||
fun updateOngoing(context: Context) {
|
||||
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return
|
||||
runCatching {
|
||||
NotificationManagerCompat.from(context).notify(ID_ONGOING, buildOngoing(context))
|
||||
}
|
||||
}
|
||||
|
||||
fun showCompletion(context: Context, finishedMode: Int, breakMinutes: Int) {
|
||||
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return
|
||||
val focusDone = finishedMode == TimerCore.MODE_FOCUS
|
||||
val title = context.getString(
|
||||
if (focusDone) R.string.notif_focus_done else R.string.notif_break_done
|
||||
)
|
||||
val text = if (focusDone) {
|
||||
context.getString(R.string.notif_focus_done_text, breakMinutes)
|
||||
} else {
|
||||
context.getString(R.string.notif_break_done_text)
|
||||
}
|
||||
val n = NotificationCompat.Builder(context, CHANNEL_ALERT)
|
||||
.setSmallIcon(R.drawable.ic_check)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setContentIntent(contentIntent(context))
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build()
|
||||
runCatching { NotificationManagerCompat.from(context).notify(ID_ALERT, n) }
|
||||
}
|
||||
|
||||
fun cancelOngoing(context: Context) {
|
||||
runCatching { NotificationManagerCompat.from(context).cancel(ID_ONGOING) }
|
||||
}
|
||||
}
|
||||
449
src/main/java/com/focusbox/app/service/TimerCore.kt
Normal file
449
src/main/java/com/focusbox/app/service/TimerCore.kt
Normal file
File diff suppressed because it is too large
Load Diff
152
src/main/java/com/focusbox/app/service/TimerService.kt
Normal file
152
src/main/java/com/focusbox/app/service/TimerService.kt
Normal file
@@ -0,0 +1,152 @@
|
||||
package com.focusbox.app.service
|
||||
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
/**
|
||||
* 计时前台服务。
|
||||
*
|
||||
* 之所以必须用前台服务而不是页面里的 Handler:息屏后 Activity 会被暂停、
|
||||
* 进程随时可能被回收,只有带常驻通知的前台服务能稳定维持计时与到时提醒。
|
||||
*
|
||||
* 真正的计时逻辑在 [TimerCore],这里只做三件事:撑住进程、每秒推进、刷新通知。
|
||||
*/
|
||||
class TimerService : Service() {
|
||||
|
||||
companion object {
|
||||
const val ACTION_SYNC = "com.focusbox.app.SYNC"
|
||||
const val ACTION_PAUSE = "com.focusbox.app.PAUSE"
|
||||
const val ACTION_RESUME = "com.focusbox.app.RESUME"
|
||||
const val ACTION_STOP = "com.focusbox.app.STOP"
|
||||
|
||||
fun ensureRunning(context: Context) {
|
||||
val intent = Intent(context, TimerService::class.java).setAction(ACTION_SYNC)
|
||||
runCatching { ContextCompat.startForegroundService(context, intent) }
|
||||
}
|
||||
|
||||
fun refresh(context: Context) {
|
||||
Notif.updateOngoing(context)
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
runCatching { context.stopService(Intent(context, TimerService::class.java)) }
|
||||
Notif.cancelOngoing(context)
|
||||
}
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
|
||||
private val ticker = object : Runnable {
|
||||
override fun run() {
|
||||
// 只推进状态,不再每秒重发通知:通知里的时间是系统的 Chronometer 在走,
|
||||
// 每秒 notify 反而会让锁屏上的计时被系统限流后"冻住"。
|
||||
TimerCore.tick()
|
||||
handler.postDelayed(this, 1000L)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
TimerCore.addListener(onStateChanged)
|
||||
}
|
||||
|
||||
private val onStateChanged: () -> Unit = {
|
||||
Notif.updateOngoing(this)
|
||||
syncWakeLock()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_PAUSE -> {
|
||||
TimerCore.pause()
|
||||
stopTicker()
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
TimerCore.resume()
|
||||
syncTicker()
|
||||
}
|
||||
ACTION_STOP -> {
|
||||
TimerCore.stopEarly()
|
||||
stopTicker()
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
|
||||
// 必须在启动后立即进入前台,否则 5 秒内会被系统判定为 ANR 级违规
|
||||
startForegroundCompat()
|
||||
syncTicker()
|
||||
syncWakeLock()
|
||||
Notif.updateOngoing(this)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/**
|
||||
* 只有倒计时需要每秒推进(判断是否到点)。
|
||||
* 正计时靠时间戳现算、通知靠系统 Chronometer 走时,
|
||||
* 既不用轮询也不用占着 WakeLock,长时间正计时不会白耗电。
|
||||
*/
|
||||
private fun syncTicker() {
|
||||
if (TimerCore.running && !TimerCore.countUp) startTicker() else stopTicker()
|
||||
}
|
||||
|
||||
private fun startForegroundCompat() {
|
||||
val notification = Notif.buildOngoing(this)
|
||||
runCatching {
|
||||
// 两参版本会读清单里声明的前台服务类型(dataSync)。
|
||||
// 不用三参 + SPECIAL_USE:该类型 Android 14 才引入,
|
||||
// 在 P30 的 Android 12 上传进去会直接抛 IllegalArgumentException。
|
||||
startForeground(Notif.ID_ONGOING, notification)
|
||||
}.onFailure {
|
||||
// 前台服务被系统拒绝(省电策略/权限)时退化为普通服务,
|
||||
// 计时本身仍在 TimerCore 里走,只是通知可能不显示。
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startTicker() {
|
||||
handler.removeCallbacks(ticker)
|
||||
handler.postDelayed(ticker, 1000L)
|
||||
}
|
||||
|
||||
private fun stopTicker() {
|
||||
handler.removeCallbacks(ticker)
|
||||
}
|
||||
|
||||
private fun syncWakeLock() {
|
||||
if (TimerCore.running && !TimerCore.countUp) {
|
||||
if (wakeLock?.isHeld != true) {
|
||||
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FocusBox:timer").apply {
|
||||
setReferenceCounted(false)
|
||||
// 超时兜底:正常路径会主动释放,这里防止异常退出后一直亮着 CPU
|
||||
acquire(4 * 60 * 60 * 1000L)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
releaseWakeLock()
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseWakeLock() {
|
||||
runCatching { if (wakeLock?.isHeld == true) wakeLock?.release() }
|
||||
wakeLock = null
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onDestroy() {
|
||||
stopTicker()
|
||||
releaseWakeLock()
|
||||
TimerCore.removeListener(onStateChanged)
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
218
src/main/java/com/focusbox/app/ui/MainActivity.kt
Normal file
218
src/main/java/com/focusbox/app/ui/MainActivity.kt
Normal file
@@ -0,0 +1,218 @@
|
||||
package com.focusbox.app.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.fragment.app.Fragment
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.ui.focus.FocusFragment
|
||||
import com.focusbox.app.ui.projects.ProjectsFragment
|
||||
import com.focusbox.app.ui.settings.SettingsFragment
|
||||
import com.focusbox.app.ui.stats.StatsFragment
|
||||
import com.focusbox.app.ui.tasks.TasksFragment
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.tint
|
||||
|
||||
/**
|
||||
* 单 Activity + 五个常驻 Fragment。
|
||||
*
|
||||
* 用 show/hide 而不是 replace:切回"任务"时滚动位置与筛选状态都还在,
|
||||
* 这对一个随手要记一笔的工具来说比省内存重要。
|
||||
*
|
||||
* 注意:切换主题会把 Activity 重建,FragmentManager 会恢复出全部片段。
|
||||
* 因此这里必须把"当前页"存进 savedInstanceState,并在 [showTab] 里显式隐藏
|
||||
* 其余所有片段——只隐藏"上一次的 current"在重建后是 null,会造成两页重叠。
|
||||
*/
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
companion object {
|
||||
const val EXTRA_TAB = "extra_tab"
|
||||
const val TAB_FOCUS = 0
|
||||
const val TAB_TASKS = 1
|
||||
const val TAB_PROJECTS = 2
|
||||
const val TAB_STATS = 3
|
||||
const val TAB_SETTINGS = 4
|
||||
private const val KEY_TAB = "current_tab"
|
||||
private const val TAB_COUNT = 5
|
||||
}
|
||||
|
||||
private lateinit var container: FrameLayout
|
||||
private lateinit var navBar: LinearLayout
|
||||
|
||||
private val fragments = arrayOfNulls<Fragment>(TAB_COUNT)
|
||||
private val navIcons = ArrayList<ImageView>()
|
||||
private val navLabels = ArrayList<TextView>()
|
||||
private var current = -1
|
||||
|
||||
private val tabLabels = intArrayOf(
|
||||
R.string.nav_focus, R.string.nav_tasks, R.string.nav_projects,
|
||||
R.string.nav_stats, R.string.nav_settings,
|
||||
)
|
||||
private val tabIcons = intArrayOf(
|
||||
R.drawable.ic_focus, R.drawable.ic_task, R.drawable.ic_project,
|
||||
R.drawable.ic_stats, R.drawable.ic_settings,
|
||||
)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
container = findViewById(R.id.container)
|
||||
navBar = findViewById(R.id.navBar)
|
||||
|
||||
buildNav()
|
||||
|
||||
val restored = savedInstanceState?.getInt(KEY_TAB, -1) ?: -1
|
||||
val fromIntent = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1
|
||||
val start = when {
|
||||
restored in 0 until TAB_COUNT -> restored
|
||||
fromIntent in 0 until TAB_COUNT -> fromIntent
|
||||
else -> TAB_FOCUS
|
||||
}
|
||||
showTab(start, force = true)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
outState.putInt(KEY_TAB, current)
|
||||
super.onSaveInstanceState(outState)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent?) {
|
||||
super.onNewIntent(intent)
|
||||
val tab = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1
|
||||
if (tab in 0 until TAB_COUNT) showTab(tab, force = true)
|
||||
}
|
||||
|
||||
private fun buildNav() {
|
||||
for (i in 0 until TAB_COUNT) {
|
||||
val item = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
gravity = Gravity.CENTER
|
||||
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)
|
||||
}
|
||||
val icon = ImageView(this).apply {
|
||||
setImageResource(tabIcons[i])
|
||||
layoutParams = LinearLayout.LayoutParams(dpi(21f), dpi(21f))
|
||||
}
|
||||
val label = TextView(this).apply {
|
||||
text = getString(tabLabels[i])
|
||||
textSize = 10f
|
||||
includeFontPadding = false
|
||||
gravity = Gravity.CENTER
|
||||
val lp = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
)
|
||||
lp.topMargin = dpi(3f)
|
||||
layoutParams = lp
|
||||
}
|
||||
item.addView(icon)
|
||||
item.addView(label)
|
||||
item.setOnClickListener { showTab(i) }
|
||||
navBar.addView(item)
|
||||
navIcons.add(icon)
|
||||
navLabels.add(label)
|
||||
}
|
||||
}
|
||||
|
||||
private fun createFragment(index: Int): Fragment = when (index) {
|
||||
0 -> FocusFragment()
|
||||
1 -> TasksFragment()
|
||||
2 -> ProjectsFragment()
|
||||
3 -> StatsFragment()
|
||||
else -> SettingsFragment()
|
||||
}
|
||||
|
||||
fun showTab(index: Int) {
|
||||
showTab(index, force = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param force 忽略"已在当前页"判断。重建、通知跳转时必须强制走一遍,
|
||||
* 否则恢复出来的其他片段不会被隐藏。
|
||||
*/
|
||||
private fun showTab(index: Int, force: Boolean) {
|
||||
if (index !in 0 until TAB_COUNT) return
|
||||
if (!force && index == current && fragments[index] != null) return
|
||||
|
||||
val fm = supportFragmentManager
|
||||
val tx = fm.beginTransaction()
|
||||
for (i in 0 until TAB_COUNT) {
|
||||
val tag = "tab$i"
|
||||
var f = fragments[i]
|
||||
if (f != null && f.isRemoving) f = null
|
||||
if (f == null) f = fm.findFragmentByTag(tag)
|
||||
if (i == index) {
|
||||
if (f == null) {
|
||||
f = createFragment(i)
|
||||
tx.add(R.id.container, f, tag)
|
||||
} else {
|
||||
tx.show(f)
|
||||
}
|
||||
fragments[i] = f
|
||||
} else if (f != null) {
|
||||
fragments[i] = f
|
||||
tx.hide(f)
|
||||
}
|
||||
}
|
||||
tx.commitNowAllowingStateLoss()
|
||||
current = index
|
||||
updateNav()
|
||||
}
|
||||
|
||||
private fun updateNav() {
|
||||
navIcons.forEachIndexed { i, icon ->
|
||||
val selected = i == current
|
||||
icon.tint(col(if (selected) R.color.brand else R.color.text_tertiary))
|
||||
navLabels[i].setTextColor(col(if (selected) R.color.brand else R.color.text_tertiary))
|
||||
navLabels[i].typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
||||
icon.alpha = if (selected) 1f else 0.85f
|
||||
}
|
||||
}
|
||||
|
||||
/** 项目页点进去看任务:切到任务页并套用该项目的筛选 */
|
||||
fun openProjectTasks(projectId: Long) {
|
||||
showTab(TAB_TASKS, force = true)
|
||||
(fragments[TAB_TASKS] as? TasksFragment)?.applyProjectFilter(projectId)
|
||||
}
|
||||
|
||||
/** 任务行的播放键:把该任务设为当前任务并回到首页,圆环套用任务时长 */
|
||||
fun startFocusOn(task: Task) {
|
||||
TimerCore.setCountUp(false)
|
||||
TimerCore.setTask(task.id, task.projectId, task.focusMinutes)
|
||||
if (!TimerCore.running && TimerCore.mode != TimerCore.MODE_FOCUS) {
|
||||
TimerCore.setMode(TimerCore.MODE_FOCUS)
|
||||
}
|
||||
showTab(TAB_FOCUS)
|
||||
}
|
||||
|
||||
fun goFocus() = showTab(TAB_FOCUS)
|
||||
|
||||
override fun onBackPressed() {
|
||||
if (current != TAB_FOCUS) {
|
||||
showTab(TAB_FOCUS)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
super.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置改动后(清空数据、改主题)统一刷新其余页面 */
|
||||
fun refreshAll() {
|
||||
for (f in fragments) {
|
||||
when (f) {
|
||||
is TasksFragment -> f.reload()
|
||||
is ProjectsFragment -> f.reload()
|
||||
is StatsFragment -> f.reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
src/main/java/com/focusbox/app/ui/SheetDialog.kt
Normal file
42
src/main/java/com/focusbox/app/ui/SheetDialog.kt
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.focusbox.app.ui
|
||||
|
||||
import android.app.Dialog
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import com.focusbox.app.R
|
||||
|
||||
/**
|
||||
* 从底部升起的弹层。
|
||||
*
|
||||
* 不用 Material 的 BottomSheetDialog:本工程刻意不引 Material 依赖(离线构建体积与
|
||||
* 主题冲突都省了),而这里只需要"贴底 + 圆角 + 键盘顶起"三件事,自己写反而可控。
|
||||
*/
|
||||
open class SheetDialog(context: Context) : Dialog(context, R.style.SheetDialog) {
|
||||
|
||||
init {
|
||||
window?.apply {
|
||||
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
|
||||
setGravity(Gravity.BOTTOM)
|
||||
setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
attributes = attributes.apply {
|
||||
width = ViewGroup.LayoutParams.MATCH_PARENT
|
||||
dimAmount = 0.45f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun setContentView(view: View) {
|
||||
super.setContentView(view)
|
||||
(view.parent as? View)?.setBackgroundColor(Color.TRANSPARENT)
|
||||
}
|
||||
|
||||
override fun show() {
|
||||
super.show()
|
||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
}
|
||||
}
|
||||
456
src/main/java/com/focusbox/app/ui/focus/FocusFragment.kt
Normal file
456
src/main/java/com/focusbox/app/ui/focus/FocusFragment.kt
Normal file
File diff suppressed because it is too large
Load Diff
71
src/main/java/com/focusbox/app/ui/projects/ProjectAdapter.kt
Normal file
71
src/main/java/com/focusbox/app/ui/projects/ProjectAdapter.kt
Normal file
@@ -0,0 +1,71 @@
|
||||
package com.focusbox.app.ui.projects
|
||||
|
||||
import android.content.res.ColorStateList
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.ImageView
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.tint
|
||||
|
||||
class ProjectAdapter(
|
||||
private val onClick: (Project) -> Unit,
|
||||
private val onLongClick: (Project) -> Unit,
|
||||
private val onMore: (Project) -> Unit,
|
||||
) : RecyclerView.Adapter<ProjectAdapter.VH>() {
|
||||
|
||||
private var items: List<Project> = emptyList()
|
||||
|
||||
fun submit(list: List<Project>) {
|
||||
items = list
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH =
|
||||
VH(LayoutInflater.from(parent.context).inflate(R.layout.item_project, parent, false))
|
||||
|
||||
override fun getItemCount(): Int = items.size
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(items[position])
|
||||
|
||||
inner class VH(v: View) : RecyclerView.ViewHolder(v) {
|
||||
private val name: TextView = v.findViewById(R.id.tvName)
|
||||
private val meta: TextView = v.findViewById(R.id.tvMeta)
|
||||
private val progress: ProgressBar = v.findViewById(R.id.progress)
|
||||
private val colorBar: View = v.findViewById(R.id.colorBar)
|
||||
private val more: ImageView = v.findViewById(R.id.btnMore)
|
||||
|
||||
fun bind(p: Project) {
|
||||
val ctx = itemView.context
|
||||
name.text = p.name
|
||||
colorBar.background = ctx.roundBg(p.color, 2f)
|
||||
|
||||
// 只看任务与时长,不再显示番茄数
|
||||
val parts = ArrayList<String>(3)
|
||||
parts.add("${p.openTasks} 待办")
|
||||
if (p.doneTasks > 0) parts.add("${p.doneTasks} 已完成")
|
||||
if (p.focusSeconds >= 60) parts.add(Dates.duration(p.focusSeconds))
|
||||
meta.text = parts.joinToString(" · ")
|
||||
|
||||
progress.progress = (p.progress * 100).toInt()
|
||||
progress.progressTintList = ColorStateList.valueOf(p.color)
|
||||
progress.progressBackgroundTintList = ColorStateList.valueOf(ctx.col(R.color.ring_track))
|
||||
|
||||
more.tint(ctx.col(R.color.text_tertiary))
|
||||
more.setOnClickListener { onMore(p) }
|
||||
|
||||
itemView.setOnClickListener { onClick(p) }
|
||||
itemView.setOnLongClickListener {
|
||||
onLongClick(p)
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
99
src/main/java/com/focusbox/app/ui/projects/ProjectSheet.kt
Normal file
99
src/main/java/com/focusbox/app/ui/projects/ProjectSheet.kt
Normal file
@@ -0,0 +1,99 @@
|
||||
package com.focusbox.app.ui.projects
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.widget.EditText
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.util.Palette
|
||||
import com.focusbox.app.util.circleBg
|
||||
import com.focusbox.app.util.dpi
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
class ProjectSheet(
|
||||
context: Context,
|
||||
private val existing: Project?,
|
||||
private val onSaved: () -> Unit,
|
||||
) : SheetDialog(context) {
|
||||
|
||||
private val root = LayoutInflater.from(context).inflate(R.layout.sheet_project, null)
|
||||
private val etName: EditText = root.findViewById(R.id.etName)
|
||||
private val colorRow: LinearLayout = root.findViewById(R.id.colorRow)
|
||||
|
||||
private var color: Int = existing?.color ?: Palette.colorAt(0)
|
||||
|
||||
init {
|
||||
setContentView(root)
|
||||
root.findViewById<TextView>(R.id.sheetTitle).setText(
|
||||
if (existing == null) R.string.add_project else R.string.edit
|
||||
)
|
||||
etName.setText(existing?.name ?: "")
|
||||
renderColors()
|
||||
|
||||
val btnDelete = root.findViewById<TextView>(R.id.btnDelete)
|
||||
val deletable = existing != null && existing.id != Store.INBOX_ID
|
||||
btnDelete.visible(deletable)
|
||||
btnDelete.setOnClickListener {
|
||||
existing ?: return@setOnClickListener
|
||||
AlertDialog.Builder(context)
|
||||
.setMessage(context.getString(R.string.delete_project_confirm, existing.name))
|
||||
.setNegativeButton(R.string.cancel, null)
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
Store.deleteProject(existing.id)
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
root.findViewById<View>(R.id.btnSave).setOnClickListener {
|
||||
val name = etName.text.toString().trim()
|
||||
if (name.isEmpty()) {
|
||||
etName.error = context.getString(R.string.project_name_hint)
|
||||
return@setOnClickListener
|
||||
}
|
||||
if (existing == null) {
|
||||
Store.addProject(name, color)
|
||||
} else {
|
||||
Store.updateProject(existing.id, name, color, existing.archived)
|
||||
}
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderColors() {
|
||||
val ctx = context
|
||||
colorRow.removeAllViews()
|
||||
Palette.colors.forEach { c ->
|
||||
val wrap = FrameLayout(ctx)
|
||||
val lp = LinearLayout.LayoutParams(dpi(40f), dpi(40f))
|
||||
lp.marginEnd = dpi(2f)
|
||||
wrap.layoutParams = lp
|
||||
wrap.background = if (c == color) ctx.roundBg(Color.TRANSPARENT, 100f, c, 2f) else null
|
||||
|
||||
val dot = View(ctx)
|
||||
val dlp = FrameLayout.LayoutParams(dpi(26f), dpi(26f))
|
||||
dlp.gravity = Gravity.CENTER
|
||||
dot.layoutParams = dlp
|
||||
dot.background = circleBg(c)
|
||||
wrap.addView(dot)
|
||||
|
||||
wrap.setOnClickListener {
|
||||
color = c
|
||||
renderColors()
|
||||
}
|
||||
colorRow.addView(wrap)
|
||||
}
|
||||
}
|
||||
}
|
||||
118
src/main/java/com/focusbox/app/ui/projects/ProjectsFragment.kt
Normal file
118
src/main/java/com/focusbox/app/ui/projects/ProjectsFragment.kt
Normal file
@@ -0,0 +1,118 @@
|
||||
package com.focusbox.app.ui.projects
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.ui.MainActivity
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
class ProjectsFragment : Fragment(R.layout.fragment_projects) {
|
||||
|
||||
private lateinit var recycler: RecyclerView
|
||||
private lateinit var tvSummary: TextView
|
||||
private lateinit var tvEmpty: TextView
|
||||
private lateinit var btnArchived: TextView
|
||||
private lateinit var adapter: ProjectAdapter
|
||||
|
||||
private var showArchived = false
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
recycler = view.findViewById(R.id.recycler)
|
||||
tvSummary = view.findViewById(R.id.tvSummary)
|
||||
tvEmpty = view.findViewById(R.id.tvEmpty)
|
||||
btnArchived = view.findViewById(R.id.btnArchived)
|
||||
|
||||
adapter = ProjectAdapter(
|
||||
onClick = { p -> (activity as? MainActivity)?.openProjectTasks(p.id) },
|
||||
onLongClick = { p -> showActions(p) },
|
||||
onMore = { p -> showActions(p) },
|
||||
)
|
||||
recycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
recycler.adapter = adapter
|
||||
recycler.itemAnimator = null
|
||||
|
||||
view.findViewById<View>(R.id.btnAdd).setOnClickListener {
|
||||
ProjectSheet(requireContext(), null) { reload() }.show()
|
||||
}
|
||||
btnArchived.setOnClickListener {
|
||||
showArchived = !showArchived
|
||||
reload()
|
||||
}
|
||||
reload()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (view != null) reload()
|
||||
}
|
||||
|
||||
override fun onHiddenChanged(hidden: Boolean) {
|
||||
super.onHiddenChanged(hidden)
|
||||
if (!hidden && view != null) reload()
|
||||
}
|
||||
|
||||
fun reload() {
|
||||
if (view == null) return
|
||||
val all = Store.projects(includeArchived = true)
|
||||
val active = all.filter { !it.archived }
|
||||
val archived = all.filter { it.archived }
|
||||
|
||||
val shown = if (showArchived) all else active
|
||||
adapter.submit(shown)
|
||||
|
||||
tvSummary.text = getString(
|
||||
R.string.project_summary, active.size, active.sumOf { it.openTasks }
|
||||
)
|
||||
tvEmpty.visible(shown.isEmpty())
|
||||
|
||||
if (archived.isEmpty()) {
|
||||
btnArchived.visible(false)
|
||||
} else {
|
||||
btnArchived.visible(true)
|
||||
btnArchived.text = if (showArchived) "隐藏已归档" else "已归档 ${archived.size}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun showActions(p: Project) {
|
||||
val isInbox = p.id == Store.INBOX_ID
|
||||
val actions = ArrayList<String>()
|
||||
actions.add(getString(R.string.edit))
|
||||
if (!isInbox) {
|
||||
actions.add(getString(if (p.archived) R.string.unarchive else R.string.archive))
|
||||
actions.add(getString(R.string.delete))
|
||||
}
|
||||
|
||||
AlertDialog.Builder(requireContext())
|
||||
.setTitle(p.name)
|
||||
.setItems(actions.toTypedArray()) { _, which ->
|
||||
when {
|
||||
which == 0 -> ProjectSheet(requireContext(), p) { reload() }.show()
|
||||
which == 1 && !isInbox -> {
|
||||
Store.updateProject(p.id, p.name, p.color, !p.archived)
|
||||
reload()
|
||||
}
|
||||
which == 2 && !isInbox -> confirmDelete(p)
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun confirmDelete(p: Project) {
|
||||
AlertDialog.Builder(requireContext())
|
||||
.setMessage(getString(R.string.delete_project_confirm, p.name))
|
||||
.setNegativeButton(R.string.cancel, null)
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
Store.deleteProject(p.id)
|
||||
reload()
|
||||
}
|
||||
.show()
|
||||
}
|
||||
}
|
||||
305
src/main/java/com/focusbox/app/ui/settings/SettingsFragment.kt
Normal file
305
src/main/java/com/focusbox/app/ui/settings/SettingsFragment.kt
Normal file
File diff suppressed because it is too large
Load Diff
340
src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt
Normal file
340
src/main/java/com/focusbox/app/ui/stats/StatsFragment.kt
Normal file
File diff suppressed because it is too large
Load Diff
154
src/main/java/com/focusbox/app/ui/tasks/TaskAdapter.kt
Normal file
154
src/main/java/com/focusbox/app/ui/tasks/TaskAdapter.kt
Normal file
@@ -0,0 +1,154 @@
|
||||
package com.focusbox.app.ui.tasks
|
||||
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.circleBg
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.roundBg
|
||||
import com.focusbox.app.util.tint
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
class TaskAdapter(
|
||||
private val onEdit: (Task) -> Unit,
|
||||
private val onToggle: (Task) -> Unit,
|
||||
private val onStart: (Task) -> Unit,
|
||||
private val onFooterClick: () -> Unit,
|
||||
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
|
||||
|
||||
sealed class Row {
|
||||
data class Item(
|
||||
val task: Task,
|
||||
val projectName: String,
|
||||
val projectColor: Int,
|
||||
val overdue: Boolean,
|
||||
/** 已完成任务的"日期 星期 起-止",无记录时为 null */
|
||||
val doneRange: String? = null,
|
||||
) : Row()
|
||||
|
||||
data class Footer(val text: String) : Row()
|
||||
}
|
||||
|
||||
private var rows: List<Row> = emptyList()
|
||||
|
||||
fun submit(list: List<Row>) {
|
||||
rows = list
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun getItemViewType(position: Int): Int =
|
||||
if (rows[position] is Row.Footer) TYPE_FOOTER else TYPE_TASK
|
||||
|
||||
override fun getItemCount(): Int = rows.size
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
|
||||
val inflater = LayoutInflater.from(parent.context)
|
||||
return if (viewType == TYPE_FOOTER) {
|
||||
FooterViewHolder(inflater.inflate(R.layout.item_footer, parent, false))
|
||||
} else {
|
||||
TaskViewHolder(inflater.inflate(R.layout.item_task, parent, false))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
|
||||
when (val row = rows[position]) {
|
||||
is Row.Item -> (holder as TaskViewHolder).bind(row)
|
||||
is Row.Footer -> (holder as FooterViewHolder).bind(row)
|
||||
}
|
||||
}
|
||||
|
||||
private inner class TaskViewHolder(v: View) : RecyclerView.ViewHolder(v) {
|
||||
private val tvTitle: TextView = v.findViewById(R.id.tvTitle)
|
||||
private val tvMeta: TextView = v.findViewById(R.id.tvMeta)
|
||||
private val tvNote: TextView = v.findViewById(R.id.tvNote)
|
||||
private val checkCircle: View = v.findViewById(R.id.checkCircle)
|
||||
private val checkMark: ImageView = v.findViewById(R.id.checkMark)
|
||||
private val checkWrap: View = v.findViewById(R.id.checkWrap)
|
||||
private val btnPlay: ImageView = v.findViewById(R.id.btnPlay)
|
||||
|
||||
fun bind(row: Row.Item) {
|
||||
val task = row.task
|
||||
val ctx = itemView.context
|
||||
|
||||
tvTitle.text = task.title
|
||||
tvTitle.paintFlags = if (task.done) {
|
||||
tvTitle.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
|
||||
} else {
|
||||
tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
|
||||
}
|
||||
tvTitle.setTextColor(ctx.col(if (task.done) R.color.text_tertiary else R.color.text))
|
||||
tvTitle.typeface = if (task.priority >= 2 && !task.done) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
||||
|
||||
if (task.done) {
|
||||
checkCircle.background = ctx.circleBg(ctx.col(R.color.brand))
|
||||
checkMark.visible(true)
|
||||
checkMark.tint(ctx.col(R.color.on_brand))
|
||||
} else {
|
||||
checkCircle.background = ctx.roundBg(
|
||||
android.graphics.Color.TRANSPARENT, 100f, ctx.col(R.color.field_stroke), 1.5f
|
||||
)
|
||||
checkMark.visible(false)
|
||||
}
|
||||
|
||||
tvMeta.text = buildMeta(row)
|
||||
tvMeta.setTextColor(
|
||||
ctx.col(
|
||||
when {
|
||||
row.overdue && !task.done -> R.color.brand
|
||||
else -> R.color.text_tertiary
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
// 备注单独一行,跟在"项目 · 日期"下面,避免挤在元信息里被截断
|
||||
tvNote.text = task.note
|
||||
tvNote.visible(task.note.isNotBlank())
|
||||
|
||||
btnPlay.visible(!task.done)
|
||||
btnPlay.tint(ctx.col(R.color.text_tertiary))
|
||||
|
||||
checkWrap.setOnClickListener { onToggle(task) }
|
||||
itemView.setOnClickListener { onEdit(task) }
|
||||
btnPlay.setOnClickListener { onStart(task) }
|
||||
}
|
||||
|
||||
private fun buildMeta(row: Row.Item): String {
|
||||
val task = row.task
|
||||
val parts = ArrayList<String>(4)
|
||||
parts.add(row.projectName)
|
||||
if (task.done) {
|
||||
row.doneRange?.let { parts.add(it) }
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
parts.add("${task.focusMinutes} 分钟")
|
||||
if (task.due > 0) {
|
||||
val label = Dates.dueLabel(task.due)
|
||||
parts.add(if (row.overdue) "已逾期 · $label" else label)
|
||||
}
|
||||
if (task.priority >= 2) parts.add("高优先")
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
}
|
||||
|
||||
private inner class FooterViewHolder(v: View) : RecyclerView.ViewHolder(v) {
|
||||
private val tv: TextView = v.findViewById(R.id.tvFooter)
|
||||
|
||||
fun bind(row: Row.Footer) {
|
||||
tv.text = row.text
|
||||
itemView.setOnClickListener { onFooterClick() }
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TYPE_TASK = 0
|
||||
private const val TYPE_FOOTER = 1
|
||||
}
|
||||
}
|
||||
233
src/main/java/com/focusbox/app/ui/tasks/TaskSheet.kt
Normal file
233
src/main/java/com/focusbox/app/ui/tasks/TaskSheet.kt
Normal file
@@ -0,0 +1,233 @@
|
||||
package com.focusbox.app.ui.tasks
|
||||
|
||||
import android.app.DatePickerDialog
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Repeat
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.service.TimerCore
|
||||
import com.focusbox.app.ui.SheetDialog
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.Prefs
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.makeChip
|
||||
import com.focusbox.app.util.visible
|
||||
import java.util.Calendar
|
||||
|
||||
/**
|
||||
* 新建 / 编辑任务。
|
||||
*
|
||||
* 项目、优先级、重复单位都用互斥胶囊,而不是下拉菜单——
|
||||
* 常用项不超过 8 个,一屏点完比"打开选择器再确认"少两次操作。
|
||||
*/
|
||||
class TaskSheet(
|
||||
context: Context,
|
||||
private val existing: Task?,
|
||||
presetProjectId: Long,
|
||||
private val onSaved: () -> Unit,
|
||||
) : SheetDialog(context) {
|
||||
|
||||
private val root = LayoutInflater.from(context).inflate(R.layout.sheet_task, null)
|
||||
|
||||
private val etTitle: EditText = root.findViewById(R.id.etTitle)
|
||||
private val etNote: EditText = root.findViewById(R.id.etNote)
|
||||
private val projectRow: LinearLayout = root.findViewById(R.id.projectRow)
|
||||
private val priorityRow: LinearLayout = root.findViewById(R.id.priorityRow)
|
||||
private val repeatRow: LinearLayout = root.findViewById(R.id.repeatRow)
|
||||
private val repeatEveryRow: View = root.findViewById(R.id.repeatEveryRow)
|
||||
private val tvFocus: TextView = root.findViewById(R.id.tvFocus)
|
||||
private val tvEvery: TextView = root.findViewById(R.id.tvEvery)
|
||||
private val btnDue: TextView = root.findViewById(R.id.btnDue)
|
||||
private val btnClearDue: View = root.findViewById(R.id.btnClearDue)
|
||||
|
||||
private var projectId: Long = existing?.projectId
|
||||
?: if (presetProjectId > 0) presetProjectId else Store.INBOX_ID
|
||||
private var priority: Int = existing?.priority ?: 1
|
||||
// 旧数据的时长可能超出新范围(早先是"番茄数×25"),这里统一夹紧
|
||||
private var focusMin: Int = (existing?.focusMinutes ?: Prefs.focusMinutes)
|
||||
.coerceIn(TimerCore.MIN_MINUTES, TimerCore.MAX_MINUTES)
|
||||
private var due: Long = existing?.due ?: 0L
|
||||
private var repeatType: Int = existing?.repeatType ?: Repeat.NONE
|
||||
private var repeatEvery: Int = existing?.repeatEvery ?: 1
|
||||
|
||||
init {
|
||||
setContentView(root)
|
||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
|
||||
root.findViewById<TextView>(R.id.sheetTitle).setText(
|
||||
if (existing == null) R.string.add_task else R.string.edit
|
||||
)
|
||||
|
||||
etTitle.setText(existing?.title ?: "")
|
||||
etNote.setText(existing?.note ?: "")
|
||||
renderFocus()
|
||||
|
||||
root.findViewById<View>(R.id.btnFocusMinus).setOnClickListener {
|
||||
focusMin = (focusMin - 5).coerceAtLeast(TimerCore.MIN_MINUTES)
|
||||
renderFocus()
|
||||
}
|
||||
root.findViewById<View>(R.id.btnFocusPlus).setOnClickListener {
|
||||
focusMin = (focusMin + 5).coerceAtMost(TimerCore.MAX_MINUTES)
|
||||
renderFocus()
|
||||
}
|
||||
|
||||
root.findViewById<View>(R.id.btnEveryMinus).setOnClickListener {
|
||||
repeatEvery = (repeatEvery - 1).coerceAtLeast(1)
|
||||
renderRepeat()
|
||||
}
|
||||
root.findViewById<View>(R.id.btnEveryPlus).setOnClickListener {
|
||||
repeatEvery = (repeatEvery + 1).coerceAtMost(30)
|
||||
renderRepeat()
|
||||
}
|
||||
|
||||
btnDue.setOnClickListener { pickDate() }
|
||||
btnClearDue.setOnClickListener {
|
||||
due = 0L
|
||||
updateDue()
|
||||
}
|
||||
|
||||
val btnDelete = root.findViewById<TextView>(R.id.btnDelete)
|
||||
btnDelete.visible(existing != null)
|
||||
btnDelete.setOnClickListener {
|
||||
AlertDialog.Builder(context)
|
||||
.setMessage(R.string.delete_task_confirm)
|
||||
.setNegativeButton(R.string.cancel, null)
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
existing?.let { Store.deleteTask(it.id) }
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
root.findViewById<View>(R.id.btnSave).setOnClickListener { save() }
|
||||
|
||||
renderProjects()
|
||||
renderPriority()
|
||||
renderRepeat()
|
||||
updateDue()
|
||||
}
|
||||
|
||||
private fun renderProjects() {
|
||||
val ctx = context
|
||||
projectRow.removeAllViews()
|
||||
Store.projects().filter { !it.archived || it.id == projectId }.forEach { p ->
|
||||
val chip = ctx.makeChip(p.name, p.id == projectId, p.color)
|
||||
chip.setOnClickListener {
|
||||
projectId = p.id
|
||||
renderProjects()
|
||||
}
|
||||
projectRow.addView(chip)
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderPriority() {
|
||||
val ctx = context
|
||||
priorityRow.removeAllViews()
|
||||
val labels = listOf(R.string.p_low, R.string.p_mid, R.string.p_high)
|
||||
labels.forEachIndexed { index, res ->
|
||||
val chip = ctx.makeChip(ctx.getString(res), index == priority)
|
||||
chip.setOnClickListener {
|
||||
priority = index
|
||||
renderPriority()
|
||||
}
|
||||
priorityRow.addView(chip)
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderFocus() {
|
||||
tvFocus.text = context.getString(R.string.minutes_value, focusMin)
|
||||
}
|
||||
|
||||
/** 重复单位四选一;选了非"不重复"才露出间隔步进器 */
|
||||
private fun renderRepeat() {
|
||||
val ctx = context
|
||||
repeatRow.removeAllViews()
|
||||
val labels = listOf(
|
||||
Repeat.NONE to R.string.repeat_none,
|
||||
Repeat.DAY to R.string.repeat_day,
|
||||
Repeat.WEEK to R.string.repeat_week,
|
||||
Repeat.MONTH to R.string.repeat_month,
|
||||
)
|
||||
labels.forEach { (type, res) ->
|
||||
val chip = ctx.makeChip(ctx.getString(res), repeatType == type)
|
||||
chip.setOnClickListener {
|
||||
repeatType = type
|
||||
renderRepeat()
|
||||
}
|
||||
repeatRow.addView(chip)
|
||||
}
|
||||
val repeating = repeatType != Repeat.NONE
|
||||
repeatEveryRow.visible(repeating)
|
||||
if (repeating) {
|
||||
val unit = ctx.getString(
|
||||
when (repeatType) {
|
||||
Repeat.WEEK -> R.string.repeat_week_unit
|
||||
Repeat.MONTH -> R.string.repeat_month_unit
|
||||
else -> R.string.repeat_day_unit
|
||||
}
|
||||
)
|
||||
tvEvery.text = "$repeatEvery $unit"
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateDue() {
|
||||
btnDue.text = if (due > 0) Dates.mdLong(due) else context.getString(R.string.no_due)
|
||||
btnDue.setTextColor(context.col(if (due > 0) R.color.text else R.color.text_secondary))
|
||||
btnClearDue.visible(due > 0)
|
||||
}
|
||||
|
||||
private fun pickDate() {
|
||||
val c = Calendar.getInstance()
|
||||
if (due > 0) c.timeInMillis = due
|
||||
DatePickerDialog(
|
||||
context,
|
||||
{ _, y, m, d ->
|
||||
val cal = Calendar.getInstance()
|
||||
cal.set(y, m, d, 0, 0, 0)
|
||||
cal.set(Calendar.MILLISECOND, 0)
|
||||
due = cal.timeInMillis
|
||||
updateDue()
|
||||
},
|
||||
c.get(Calendar.YEAR),
|
||||
c.get(Calendar.MONTH),
|
||||
c.get(Calendar.DAY_OF_MONTH),
|
||||
).show()
|
||||
}
|
||||
|
||||
private fun save() {
|
||||
val title = etTitle.text.toString().trim()
|
||||
if (title.isEmpty()) {
|
||||
etTitle.error = context.getString(R.string.task_title_hint)
|
||||
return
|
||||
}
|
||||
val note = etNote.text.toString().trim()
|
||||
val every = if (repeatType == Repeat.NONE) 1 else repeatEvery.coerceAtLeast(1)
|
||||
if (existing == null) {
|
||||
Store.addTask(title, note, projectId, priority, focusMin, due, repeatType, every)
|
||||
} else {
|
||||
Store.updateTask(
|
||||
existing.copy(
|
||||
title = title,
|
||||
note = note,
|
||||
projectId = projectId,
|
||||
priority = priority,
|
||||
focusMinutes = focusMin,
|
||||
due = due,
|
||||
repeatType = repeatType,
|
||||
repeatEvery = every,
|
||||
)
|
||||
)
|
||||
}
|
||||
onSaved()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
212
src/main/java/com/focusbox/app/ui/tasks/TasksFragment.kt
Normal file
212
src/main/java/com/focusbox/app/ui/tasks/TasksFragment.kt
Normal file
@@ -0,0 +1,212 @@
|
||||
package com.focusbox.app.ui.tasks
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.data.Store
|
||||
import com.focusbox.app.model.Project
|
||||
import com.focusbox.app.model.SessionSpan
|
||||
import com.focusbox.app.model.Task
|
||||
import com.focusbox.app.ui.MainActivity
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.makeChip
|
||||
import com.focusbox.app.util.visible
|
||||
|
||||
/**
|
||||
* 任务页。
|
||||
*
|
||||
* 顶部胶囊分两组:
|
||||
* - 视图:全部 / 今日 / 已完成
|
||||
* - 项目:收件箱与各项目
|
||||
* 视图与项目互斥,选了项目就回到"全部",避免出现"今日 + 某项目"这种没人能解释的组合。
|
||||
*/
|
||||
class TasksFragment : Fragment(R.layout.fragment_tasks) {
|
||||
|
||||
private enum class ViewFilter { ALL, TODAY, DONE }
|
||||
|
||||
private lateinit var recycler: RecyclerView
|
||||
private lateinit var tvCount: TextView
|
||||
private lateinit var tvEmpty: TextView
|
||||
private lateinit var chipRow: LinearLayout
|
||||
|
||||
private lateinit var adapter: TaskAdapter
|
||||
|
||||
private var filterProjectId = 0L
|
||||
private var viewFilter = ViewFilter.ALL
|
||||
private var expandedDone = false
|
||||
private var projects: List<Project> = emptyList()
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
recycler = view.findViewById(R.id.recycler)
|
||||
tvCount = view.findViewById(R.id.tvCount)
|
||||
tvEmpty = view.findViewById(R.id.tvEmpty)
|
||||
chipRow = view.findViewById(R.id.chipRow)
|
||||
|
||||
adapter = TaskAdapter(
|
||||
onEdit = { openSheet(it) },
|
||||
onToggle = { task ->
|
||||
Store.setTaskDone(task.id, !task.done)
|
||||
reload()
|
||||
},
|
||||
onStart = { task -> (activity as? MainActivity)?.startFocusOn(task) },
|
||||
onFooterClick = {
|
||||
expandedDone = !expandedDone
|
||||
reload()
|
||||
},
|
||||
)
|
||||
recycler.layoutManager = LinearLayoutManager(requireContext())
|
||||
recycler.adapter = adapter
|
||||
recycler.itemAnimator = null
|
||||
|
||||
view.findViewById<View>(R.id.btnAdd).setOnClickListener {
|
||||
TaskSheet(requireContext(), null, filterProjectId) { reload() }.show()
|
||||
}
|
||||
reload()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (view != null) reload()
|
||||
}
|
||||
|
||||
override fun onHiddenChanged(hidden: Boolean) {
|
||||
super.onHiddenChanged(hidden)
|
||||
if (!hidden && view != null) reload()
|
||||
}
|
||||
|
||||
/** 从项目页点进来:只看这个项目的全部任务 */
|
||||
fun applyProjectFilter(projectId: Long) {
|
||||
filterProjectId = projectId
|
||||
viewFilter = ViewFilter.ALL
|
||||
if (view != null) reload()
|
||||
}
|
||||
|
||||
fun reload() {
|
||||
if (view == null) return
|
||||
projects = Store.projects()
|
||||
renderChips()
|
||||
|
||||
val all = Store.tasks(filterProjectId, includeDone = true)
|
||||
val pending = all.filter { !it.done }
|
||||
val done = all.filter { it.done }
|
||||
val spans = if (done.isEmpty()) emptyMap() else Store.lastSessions()
|
||||
|
||||
val rows = ArrayList<TaskAdapter.Row>()
|
||||
|
||||
when (viewFilter) {
|
||||
ViewFilter.ALL -> {
|
||||
pending.forEach { rows.add(toRow(it, spans)) }
|
||||
tvCount.text = getString(R.string.task_count, pending.size)
|
||||
tvEmpty.setText(R.string.empty_tasks)
|
||||
if (done.isNotEmpty()) {
|
||||
if (expandedDone) done.forEach { rows.add(toRow(it, spans)) }
|
||||
rows.add(
|
||||
TaskAdapter.Row.Footer(
|
||||
getString(if (expandedDone) R.string.hide_done else R.string.show_done)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
ViewFilter.TODAY -> {
|
||||
val from = Dates.todayStart()
|
||||
val to = Dates.addDays(from, 1)
|
||||
val today = pending.filter { it.due >= from && it.due < to }
|
||||
today.forEach { rows.add(toRow(it, spans)) }
|
||||
tvCount.text = getString(R.string.task_count_today, today.size)
|
||||
tvEmpty.setText(R.string.empty_today)
|
||||
}
|
||||
|
||||
ViewFilter.DONE -> {
|
||||
done.forEach { rows.add(toRow(it, spans)) }
|
||||
tvCount.text = getString(R.string.task_count_done, done.size)
|
||||
tvEmpty.setText(R.string.empty_done)
|
||||
}
|
||||
}
|
||||
|
||||
adapter.submit(rows)
|
||||
tvEmpty.visible(rows.isEmpty())
|
||||
recycler.visible(rows.isNotEmpty())
|
||||
}
|
||||
|
||||
private fun toRow(task: Task, spans: Map<Long, SessionSpan>): TaskAdapter.Row.Item {
|
||||
val project = projects.firstOrNull { it.id == task.projectId }
|
||||
val overdue = task.due > 0 && task.due < Dates.todayStart()
|
||||
return TaskAdapter.Row.Item(
|
||||
task = task,
|
||||
projectName = project?.name ?: getString(R.string.inbox),
|
||||
projectColor = project?.color ?: 0xFF7A756C.toInt(),
|
||||
overdue = overdue,
|
||||
doneRange = if (task.done) doneRange(task, spans) else null,
|
||||
)
|
||||
}
|
||||
|
||||
/** 11月27日 周五 09:12:03-09:37:03 */
|
||||
private fun doneRange(task: Task, spans: Map<Long, SessionSpan>): String? {
|
||||
val span = spans[task.id]
|
||||
if (span != null) {
|
||||
return "${Dates.dateWithWeek(span.startAt)} " +
|
||||
"${Dates.hms(span.startAt)}-${Dates.hms(span.endAt)}"
|
||||
}
|
||||
if (task.doneAt > 0) {
|
||||
return "${Dates.dateWithWeek(task.doneAt)} ${Dates.hms(task.doneAt)}"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun renderChips() {
|
||||
chipRow.removeAllViews()
|
||||
val allSelected = viewFilter == ViewFilter.ALL && filterProjectId == 0L
|
||||
chipRow.addView(
|
||||
requireContext().makeChip(getString(R.string.filter_all), allSelected)
|
||||
.also {
|
||||
it.setOnClickListener {
|
||||
viewFilter = ViewFilter.ALL
|
||||
filterProjectId = 0L
|
||||
reload()
|
||||
}
|
||||
}
|
||||
)
|
||||
chipRow.addView(
|
||||
requireContext().makeChip(getString(R.string.filter_today), viewFilter == ViewFilter.TODAY)
|
||||
.also {
|
||||
it.setOnClickListener {
|
||||
viewFilter = ViewFilter.TODAY
|
||||
filterProjectId = 0L
|
||||
reload()
|
||||
}
|
||||
}
|
||||
)
|
||||
chipRow.addView(
|
||||
requireContext().makeChip(getString(R.string.filter_done), viewFilter == ViewFilter.DONE)
|
||||
.also {
|
||||
it.setOnClickListener {
|
||||
viewFilter = ViewFilter.DONE
|
||||
filterProjectId = 0L
|
||||
reload()
|
||||
}
|
||||
}
|
||||
)
|
||||
projects.forEach { p ->
|
||||
if (p.archived) return@forEach
|
||||
val selected = viewFilter == ViewFilter.ALL && filterProjectId == p.id
|
||||
val chip = requireContext().makeChip(p.name, selected, p.color)
|
||||
chip.setOnClickListener {
|
||||
viewFilter = ViewFilter.ALL
|
||||
filterProjectId = p.id
|
||||
reload()
|
||||
}
|
||||
chipRow.addView(chip)
|
||||
}
|
||||
}
|
||||
|
||||
private fun openSheet(task: Task?) {
|
||||
TaskSheet(requireContext(), task, filterProjectId) { reload() }.show()
|
||||
}
|
||||
}
|
||||
44
src/main/java/com/focusbox/app/util/Chips.kt
Normal file
44
src/main/java/com/focusbox/app/util/Chips.kt
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.focusbox.app.R
|
||||
|
||||
/** 小圆点,用作项目标记 */
|
||||
fun Context.dotDrawable(color: Int, sizeDp: Float = 8f): Drawable = GradientDrawable().apply {
|
||||
shape = GradientDrawable.OVAL
|
||||
setColor(color)
|
||||
setSize(dpi(sizeDp), dpi(sizeDp))
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一的筛选胶囊。选中态用浅品牌底 + 品牌描边,
|
||||
* 未选中是白底细描边——比 Material Chip 少一层阴影,在浅底上更干净。
|
||||
*/
|
||||
fun Context.makeChip(text: String, selected: Boolean, dotColor: Int? = null): TextView =
|
||||
TextView(this).apply {
|
||||
this.text = text
|
||||
textSize = 12.5f
|
||||
gravity = android.view.Gravity.CENTER
|
||||
setTextColor(col(if (selected) R.color.brand else R.color.text_secondary))
|
||||
background = ContextCompat.getDrawable(
|
||||
this@makeChip,
|
||||
if (selected) R.drawable.bg_chip_on else R.drawable.bg_chip_off,
|
||||
)
|
||||
setPadding(dpi(12f), dpi(7f), dpi(12f), dpi(7f))
|
||||
if (dotColor != null) {
|
||||
val d = this@makeChip.dotDrawable(dotColor)
|
||||
setCompoundDrawablesRelativeWithIntrinsicBounds(d, null, null, null)
|
||||
compoundDrawablePadding = dpi(5f)
|
||||
}
|
||||
val lp = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
)
|
||||
lp.marginEnd = dpi(8f)
|
||||
layoutParams = lp
|
||||
}
|
||||
125
src/main/java/com/focusbox/app/util/Dates.kt
Normal file
125
src/main/java/com/focusbox/app/util/Dates.kt
Normal file
@@ -0,0 +1,125 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/** 时间格式化与"自然日"边界计算,全局只此一份,避免各处口径不一。 */
|
||||
object Dates {
|
||||
|
||||
private val keyFmt = SimpleDateFormat("yyyy-MM-dd", Locale.US)
|
||||
private val mdFmt = SimpleDateFormat("M/d", Locale.CHINA)
|
||||
private val mdFmt2 = SimpleDateFormat("M月d日", Locale.CHINA)
|
||||
private val hmFmt = SimpleDateFormat("HH:mm", Locale.CHINA)
|
||||
private val hmsFmt = SimpleDateFormat("HH:mm:ss", Locale.CHINA)
|
||||
|
||||
fun dayKey(ms: Long): String = keyFmt.format(Date(ms))
|
||||
|
||||
fun dayStart(ms: Long): Long {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = ms
|
||||
c.set(Calendar.HOUR_OF_DAY, 0)
|
||||
c.set(Calendar.MINUTE, 0)
|
||||
c.set(Calendar.SECOND, 0)
|
||||
c.set(Calendar.MILLISECOND, 0)
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
fun dayStartOfKey(key: String): Long = keyFmt.parse(key)?.time ?: 0L
|
||||
|
||||
fun todayStart(): Long = dayStart(System.currentTimeMillis())
|
||||
|
||||
/** 本周一 00:00(周一为一周起点,符合国内习惯) */
|
||||
fun weekStart(): Long {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = todayStart()
|
||||
val dow = c.get(Calendar.DAY_OF_WEEK) // 1=周日
|
||||
val back = if (dow == Calendar.SUNDAY) 6 else dow - 2
|
||||
c.add(Calendar.DAY_OF_MONTH, -back)
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
fun monthStart(): Long {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = todayStart()
|
||||
c.set(Calendar.DAY_OF_MONTH, 1)
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
fun addDays(ms: Long, days: Int): Long {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = ms
|
||||
c.add(Calendar.DAY_OF_MONTH, days)
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
/** 月末会按当月最后一天收敛(1月31日 + 1月 = 2月28/29日),不会溢出到下个月 */
|
||||
fun addMonths(ms: Long, months: Int): Long {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = ms
|
||||
c.add(Calendar.MONTH, months)
|
||||
return c.timeInMillis
|
||||
}
|
||||
|
||||
/** 12:30 这种时钟显示;不足 10 分钟显示 09:30 两位分 */
|
||||
fun clock(ms: Long): String {
|
||||
val total = (ms / 1000).coerceAtLeast(0)
|
||||
val m = total / 60
|
||||
val s = total % 60
|
||||
return String.format(Locale.US, "%02d:%02d", m, s)
|
||||
}
|
||||
|
||||
/** 45m / 2h10m / 12.5h,统计里统一用这个口径 */
|
||||
fun duration(seconds: Int): String {
|
||||
if (seconds < 60) return "${seconds}秒"
|
||||
val minutes = seconds / 60
|
||||
if (minutes < 60) return "${minutes}分钟"
|
||||
val h = minutes / 60
|
||||
val m = minutes % 60
|
||||
return if (m == 0) "${h}小时" else "${h}小时${m}分"
|
||||
}
|
||||
|
||||
/** 图表坐标轴用的短格式:2h / 45m */
|
||||
fun shortDuration(seconds: Int): String {
|
||||
if (seconds <= 0) return "0"
|
||||
val minutes = seconds / 60
|
||||
if (minutes < 60) return "${minutes}m"
|
||||
val h = minutes / 60f
|
||||
return if (h >= 10) "${h.toInt()}h" else String.format(Locale.US, "%.1fh", h)
|
||||
}
|
||||
|
||||
fun md(ms: Long): String = mdFmt.format(Date(ms))
|
||||
fun mdLong(ms: Long): String = mdFmt2.format(Date(ms))
|
||||
fun hm(ms: Long): String = hmFmt.format(Date(ms))
|
||||
fun hms(ms: Long): String = hmsFmt.format(Date(ms))
|
||||
|
||||
/** 周五 / 周一 */
|
||||
fun weekday(ms: Long): String {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = ms
|
||||
return arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")[
|
||||
(c.get(Calendar.DAY_OF_WEEK) - 1).coerceIn(0, 6)
|
||||
]
|
||||
}
|
||||
|
||||
/** 11月27日 周五 */
|
||||
fun dateWithWeek(ms: Long): String = "${mdLong(ms)} ${weekday(ms)}"
|
||||
|
||||
/** 今天 / 明天 / 已逾期 / 11月30日 */
|
||||
fun dueLabel(due: Long): String {
|
||||
if (due <= 0) return ""
|
||||
val today = todayStart()
|
||||
val d = dayStart(due)
|
||||
return when {
|
||||
d == today -> "今天"
|
||||
d == addDays(today, 1) -> "明天"
|
||||
d == addDays(today, -1) -> "昨天"
|
||||
d < today -> md(d)
|
||||
else -> md(d)
|
||||
}
|
||||
}
|
||||
|
||||
fun weekdayShort(index: Int): String =
|
||||
arrayOf("一", "二", "三", "四", "五", "六", "日")[index.coerceIn(0, 6)]
|
||||
}
|
||||
21
src/main/java/com/focusbox/app/util/Palette.kt
Normal file
21
src/main/java/com/focusbox/app/util/Palette.kt
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
/** 项目配色。八色一组,两两之间在色相上有足够间距,圆点上也能分辨。 */
|
||||
object Palette {
|
||||
|
||||
val colors = intArrayOf(
|
||||
0xFFC75B45.toInt(), // 陶土红
|
||||
0xFFD98324.toInt(), // 琥珀
|
||||
0xFFC9A227.toInt(), // 芥黄
|
||||
0xFF4C8C4A.toInt(), // 苔绿
|
||||
0xFF3F7F6E.toInt(), // 松石
|
||||
0xFF3B7DD8.toInt(), // 靛蓝
|
||||
0xFF6C5CE7.toInt(), // 紫
|
||||
0xFFB7548E.toInt(), // 玫红
|
||||
)
|
||||
|
||||
/** 收件箱用中性灰,避免和自建项目争注意力 */
|
||||
const val INBOX = 0xFF7A756C.toInt()
|
||||
|
||||
fun colorAt(index: Int): Int = colors[index.mod(colors.size)]
|
||||
}
|
||||
125
src/main/java/com/focusbox/app/util/Prefs.kt
Normal file
125
src/main/java/com/focusbox/app/util/Prefs.kt
Normal file
@@ -0,0 +1,125 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
/**
|
||||
* 全部可调项与计时状态的落盘位置。
|
||||
*
|
||||
* 计时状态必须持久化:息屏被杀进程后重新打开,仍要能接着走同一个番茄,
|
||||
* 否则用户会看到一个"自己重新开始"的计时器。
|
||||
*/
|
||||
object Prefs {
|
||||
|
||||
private lateinit var sp: SharedPreferences
|
||||
|
||||
fun init(context: Context) {
|
||||
sp = context.getSharedPreferences("focusbox", Context.MODE_PRIVATE)
|
||||
}
|
||||
|
||||
// ---- 时长 ----
|
||||
var focusMinutes: Int
|
||||
get() = sp.getInt("focus_minutes", 25)
|
||||
set(v) = sp.edit().putInt("focus_minutes", v.coerceIn(5, 180)).apply()
|
||||
|
||||
var shortBreakMinutes: Int
|
||||
get() = sp.getInt("short_break", 5)
|
||||
set(v) = sp.edit().putInt("short_break", v.coerceIn(1, 60)).apply()
|
||||
|
||||
var longBreakMinutes: Int
|
||||
get() = sp.getInt("long_break", 15)
|
||||
set(v) = sp.edit().putInt("long_break", v.coerceIn(5, 90)).apply()
|
||||
|
||||
var longBreakEvery: Int
|
||||
get() = sp.getInt("long_every", 4)
|
||||
set(v) = sp.edit().putInt("long_every", v.coerceIn(2, 8)).apply()
|
||||
|
||||
// ---- 自动衔接 ----
|
||||
var autoStartBreak: Boolean
|
||||
get() = sp.getBoolean("auto_break", true)
|
||||
set(v) = sp.edit().putBoolean("auto_break", v).apply()
|
||||
|
||||
var autoStartFocus: Boolean
|
||||
get() = sp.getBoolean("auto_focus", false)
|
||||
set(v) = sp.edit().putBoolean("auto_focus", v).apply()
|
||||
|
||||
// ---- 提醒 ----
|
||||
var soundOn: Boolean
|
||||
get() = sp.getBoolean("sound", true)
|
||||
set(v) = sp.edit().putBoolean("sound", v).apply()
|
||||
|
||||
var vibrateOn: Boolean
|
||||
get() = sp.getBoolean("vibrate", true)
|
||||
set(v) = sp.edit().putBoolean("vibrate", v).apply()
|
||||
|
||||
var keepScreenOn: Boolean
|
||||
get() = sp.getBoolean("keep_screen", true)
|
||||
set(v) = sp.edit().putBoolean("keep_screen", v).apply()
|
||||
|
||||
// ---- 目标 ----
|
||||
var dailyGoalMinutes: Int
|
||||
get() = sp.getInt("daily_goal", 120)
|
||||
set(v) = sp.edit().putInt("daily_goal", v.coerceIn(15, 720)).apply()
|
||||
|
||||
/** 0 跟随系统 / 1 浅色 / 2 深色 */
|
||||
var themeMode: Int
|
||||
get() = sp.getInt("theme_mode", 0)
|
||||
set(v) = sp.edit().putInt("theme_mode", v).apply()
|
||||
|
||||
// ---- 计时状态 ----
|
||||
var timerMode: Int
|
||||
get() = sp.getInt("t_mode", 0)
|
||||
set(v) = sp.edit().putInt("t_mode", v).apply()
|
||||
|
||||
var timerRunning: Boolean
|
||||
get() = sp.getBoolean("t_running", false)
|
||||
set(v) = sp.edit().putBoolean("t_running", v).apply()
|
||||
|
||||
var timerTotalMs: Long
|
||||
get() = sp.getLong("t_total", 0L)
|
||||
set(v) = sp.edit().putLong("t_total", v).apply()
|
||||
|
||||
var timerRemainingMs: Long
|
||||
get() = sp.getLong("t_remaining", 0L)
|
||||
set(v) = sp.edit().putLong("t_remaining", v).apply()
|
||||
|
||||
var timerEndAt: Long
|
||||
get() = sp.getLong("t_end", 0L)
|
||||
set(v) = sp.edit().putLong("t_end", v).apply()
|
||||
|
||||
var timerTaskId: Long
|
||||
get() = sp.getLong("t_task", 0L)
|
||||
set(v) = sp.edit().putLong("t_task", v).apply()
|
||||
|
||||
var timerProjectId: Long
|
||||
get() = sp.getLong("t_project", 0L)
|
||||
set(v) = sp.edit().putLong("t_project", v).apply()
|
||||
|
||||
var timerRound: Int
|
||||
get() = sp.getInt("t_round", 0)
|
||||
set(v) = sp.edit().putInt("t_round", v).apply()
|
||||
|
||||
var timerStartedAt: Long
|
||||
get() = sp.getLong("t_started", 0L)
|
||||
set(v) = sp.edit().putLong("t_started", v).apply()
|
||||
|
||||
/** 是否处于正计时(秒表)页 */
|
||||
var timerCountUp: Boolean
|
||||
get() = sp.getBoolean("t_countup", false)
|
||||
set(v) = sp.edit().putBoolean("t_countup", v).apply()
|
||||
|
||||
/** 正计时的累计毫秒(暂停时保存的值) */
|
||||
var timerAccumMs: Long
|
||||
get() = sp.getLong("t_accum", 0L)
|
||||
set(v) = sp.edit().putLong("t_accum", v).apply()
|
||||
|
||||
fun clearTimer() {
|
||||
sp.edit()
|
||||
.putBoolean("t_running", false)
|
||||
.putLong("t_remaining", 0L)
|
||||
.putLong("t_end", 0L)
|
||||
.putLong("t_started", 0L)
|
||||
.putLong("t_accum", 0L)
|
||||
.apply()
|
||||
}
|
||||
}
|
||||
97
src/main/java/com/focusbox/app/util/Ui.kt
Normal file
97
src/main/java/com/focusbox/app/util/Ui.kt
Normal file
@@ -0,0 +1,97 @@
|
||||
package com.focusbox.app.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.util.TypedValue
|
||||
import android.view.View
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.ColorRes
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.drawable.DrawableCompat
|
||||
|
||||
fun Context.dpf(v: Float): Float = v * resources.displayMetrics.density
|
||||
|
||||
fun Context.dpi(v: Float): Int = (v * resources.displayMetrics.density).toInt()
|
||||
|
||||
fun Context.col(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)
|
||||
|
||||
fun Context.spf(v: Float): Float = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_SP, v, resources.displayMetrics
|
||||
)
|
||||
|
||||
/*
|
||||
* 下面几组重载不是冗余:布局代码大量写在 `LinearLayout(ctx).apply { ... }` 里,
|
||||
* 此时隐式接收者是 View 而不是 Context,只留 Context 版本会导致 dpi/col 全部解析失败。
|
||||
* Fragment 版本覆盖 `LinearLayout.LayoutParams(...).apply { marginStart = dpi(4f) }`
|
||||
* 这类接收者既不是 View 也不是 Context 的场景。
|
||||
*/
|
||||
|
||||
fun View.dpi(v: Float): Int = context.dpi(v)
|
||||
|
||||
fun View.col(@ColorRes id: Int): Int = context.col(id)
|
||||
|
||||
fun androidx.fragment.app.Fragment.dpi(v: Float): Int = requireContext().dpi(v)
|
||||
|
||||
fun androidx.fragment.app.Fragment.col(@ColorRes id: Int): Int = requireContext().col(id)
|
||||
|
||||
fun android.app.Dialog.dpi(v: Float): Int = context.dpi(v)
|
||||
|
||||
fun android.app.Dialog.col(@ColorRes id: Int): Int = context.col(id)
|
||||
|
||||
/** 圆角面板 / 药丸 / 圆点,全部用代码生成,避免为每种尺寸再建一个 drawable */
|
||||
fun Context.roundBg(color: Int, radiusDp: Float, strokeColor: Int? = null, strokeDp: Float = 1f): GradientDrawable =
|
||||
GradientDrawable().apply {
|
||||
shape = GradientDrawable.RECTANGLE
|
||||
cornerRadius = dpf(radiusDp)
|
||||
setColor(color)
|
||||
if (strokeColor != null) setStroke(dpi(strokeDp).coerceAtLeast(1), strokeColor)
|
||||
}
|
||||
|
||||
fun View.roundBg(color: Int, radiusDp: Float, strokeColor: Int? = null, strokeDp: Float = 1f): GradientDrawable =
|
||||
context.roundBg(color, radiusDp, strokeColor, strokeDp)
|
||||
|
||||
fun androidx.fragment.app.Fragment.roundBg(
|
||||
color: Int,
|
||||
radiusDp: Float,
|
||||
strokeColor: Int? = null,
|
||||
strokeDp: Float = 1f,
|
||||
): GradientDrawable = requireContext().roundBg(color, radiusDp, strokeColor, strokeDp)
|
||||
|
||||
fun android.app.Dialog.roundBg(
|
||||
color: Int,
|
||||
radiusDp: Float,
|
||||
strokeColor: Int? = null,
|
||||
strokeDp: Float = 1f,
|
||||
): GradientDrawable = context.roundBg(color, radiusDp, strokeColor, strokeDp)
|
||||
|
||||
fun Context.circleBg(color: Int): GradientDrawable = GradientDrawable().apply {
|
||||
shape = GradientDrawable.OVAL
|
||||
setColor(color)
|
||||
}
|
||||
|
||||
fun View.circleBg(color: Int): GradientDrawable = context.circleBg(color)
|
||||
|
||||
fun androidx.fragment.app.Fragment.circleBg(color: Int): GradientDrawable = requireContext().circleBg(color)
|
||||
|
||||
fun android.app.Dialog.circleBg(color: Int): GradientDrawable = context.circleBg(color)
|
||||
|
||||
fun ImageView.tint(color: Int) {
|
||||
val d = drawable ?: return
|
||||
val wrapped = DrawableCompat.wrap(d.mutate())
|
||||
DrawableCompat.setTint(wrapped, color)
|
||||
setImageDrawable(wrapped)
|
||||
}
|
||||
|
||||
fun View.visible(show: Boolean) {
|
||||
visibility = if (show) View.VISIBLE else View.GONE
|
||||
}
|
||||
|
||||
/** 统一的行内边距换算,保证不同布局的 16dp 是同一个 16dp */
|
||||
fun View.pad(h: Float, v: Float) {
|
||||
setPadding(context.dpi(h), context.dpi(v), context.dpi(h), context.dpi(v))
|
||||
}
|
||||
|
||||
fun TextView.setAlphaCompat(a: Float) {
|
||||
alpha = a
|
||||
}
|
||||
242
src/main/java/com/focusbox/app/widget/Charts.kt
Normal file
242
src/main/java/com/focusbox/app/widget/Charts.kt
Normal file
@@ -0,0 +1,242 @@
|
||||
package com.focusbox.app.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.model.DayPoint
|
||||
import com.focusbox.app.model.ProjectSlice
|
||||
import com.focusbox.app.util.Dates
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpf
|
||||
import com.focusbox.app.util.spf
|
||||
import java.util.Calendar
|
||||
|
||||
/** 趋势柱状图:支持 7 / 30 天,柱脚标签按密度抽稀,柱子不会挤成一片色块。 */
|
||||
class BarChartView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
) : View(context, attrs) {
|
||||
|
||||
private data class Bar(val label: String, val value: Int)
|
||||
|
||||
private var bars: List<Bar> = emptyList()
|
||||
|
||||
private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val gridPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = context.dpf(1f)
|
||||
color = context.col(R.color.divider)
|
||||
}
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(10f)
|
||||
color = context.col(R.color.text_tertiary)
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
private val valuePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(10f)
|
||||
color = context.col(R.color.text_secondary)
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
fun setData(points: List<DayPoint>) {
|
||||
bars = points.map { Bar(it.label, it.minutes) }
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
if (bars.isEmpty()) return
|
||||
|
||||
val labelH = context.dpf(20f)
|
||||
val topPad = context.dpf(18f)
|
||||
val baseY = height - labelH
|
||||
val usableH = baseY - topPad
|
||||
val brand = context.col(R.color.brand)
|
||||
val soft = context.col(R.color.brand_soft)
|
||||
val peak = (bars.maxOfOrNull { it.value } ?: 0).coerceAtLeast(30)
|
||||
|
||||
// 两条参考线:一半与峰顶,给出高度感又不喧宾夺主
|
||||
gridPaint.color = context.col(R.color.divider)
|
||||
canvas.drawLine(0f, baseY, width.toFloat(), baseY, gridPaint)
|
||||
canvas.drawLine(0f, baseY - usableH / 2f, width.toFloat(), baseY - usableH / 2f, gridPaint)
|
||||
|
||||
val n = bars.size
|
||||
val slot = width.toFloat() / n
|
||||
val barW = (slot * if (n <= 7) 0.42f else 0.62f).coerceAtLeast(context.dpf(2f))
|
||||
val radius = minOf(barW / 2f, context.dpf(4f))
|
||||
val lastIndex = n - 1
|
||||
|
||||
bars.forEachIndexed { i, bar ->
|
||||
val cx = slot * i + slot / 2f
|
||||
val h = (bar.value.toFloat() / peak * usableH).coerceAtLeast(if (bar.value > 0) context.dpf(2f) else 0f)
|
||||
if (h > 0f) {
|
||||
barPaint.color = if (i == lastIndex) brand else soft
|
||||
val r = RectF(cx - barW / 2f, baseY - h, cx + barW / 2f, baseY)
|
||||
canvas.drawRoundRect(r, radius, radius, barPaint)
|
||||
}
|
||||
|
||||
if (n <= 7) {
|
||||
if (bar.value > 0) {
|
||||
valuePaint.color = context.col(R.color.text_secondary)
|
||||
canvas.drawText("${bar.value}", cx, baseY - h - context.dpf(5f), valuePaint)
|
||||
}
|
||||
textPaint.color = context.col(R.color.text_tertiary)
|
||||
canvas.drawText(bar.label, cx, height - context.dpf(5f), textPaint)
|
||||
} else if (i % 5 == 0 || i == lastIndex) {
|
||||
textPaint.color = context.col(R.color.text_tertiary)
|
||||
canvas.drawText(bar.label, cx, height - context.dpf(5f), textPaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 打卡热力图:7 行(周一…周日)× N 列(周),色阶五档。 */
|
||||
class HeatmapView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
) : View(context, attrs) {
|
||||
|
||||
private var days: List<DayPoint> = emptyList()
|
||||
|
||||
private val cellPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(9f)
|
||||
color = context.col(R.color.text_tertiary)
|
||||
textAlign = Paint.Align.RIGHT
|
||||
}
|
||||
|
||||
private var levels = intArrayOf(
|
||||
context.col(R.color.heat0),
|
||||
context.col(R.color.heat1),
|
||||
context.col(R.color.heat2),
|
||||
context.col(R.color.heat3),
|
||||
context.col(R.color.heat4),
|
||||
)
|
||||
|
||||
fun setData(points: List<DayPoint>) {
|
||||
days = points
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun levelOf(minutes: Int): Int = when {
|
||||
minutes <= 0 -> 0
|
||||
minutes < 25 -> 1
|
||||
minutes < 50 -> 2
|
||||
minutes < 90 -> 3
|
||||
else -> 4
|
||||
}
|
||||
|
||||
private fun weekdayIndex(ms: Long): Int {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = ms
|
||||
val dow = c.get(Calendar.DAY_OF_WEEK)
|
||||
return if (dow == Calendar.SUNDAY) 6 else dow - 2
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
if (days.isEmpty()) return
|
||||
|
||||
val labelW = context.dpf(16f)
|
||||
val gap = context.dpf(3f)
|
||||
val top = context.dpf(2f)
|
||||
val firstMs = Dates.dayStartOfKey(days.first().key)
|
||||
val startCol = weekdayIndex(firstMs) // 第一列从周一算起,前面留空
|
||||
val totalCells = startCol + days.size
|
||||
val cols = (totalCells + 6) / 7
|
||||
val cellW = (width - labelW - gap * (cols - 1)) / cols
|
||||
// 高度也要参与取小:宽屏时按宽度算出的格子会把第 7 行挤出可视区
|
||||
val cellH = (height - top - gap * 6) / 7f
|
||||
val cell = minOf(cellW.toFloat(), cellH, context.dpf(15f))
|
||||
val radius = cell * 0.28f
|
||||
|
||||
val rect = RectF()
|
||||
days.forEachIndexed { i, d ->
|
||||
val pos = startCol + i
|
||||
val col = pos / 7
|
||||
val row = pos % 7
|
||||
val x = labelW + col * (cell + gap)
|
||||
val y = top + row * (cell + gap)
|
||||
cellPaint.color = levels[levelOf(d.minutes)]
|
||||
rect.set(x, y, x + cell, y + cell)
|
||||
canvas.drawRoundRect(rect, radius, radius, cellPaint)
|
||||
}
|
||||
|
||||
// 只在周一/三/五标字,避免七行小字糊在一起
|
||||
val labels = mapOf(0 to "一", 2 to "三", 4 to "五")
|
||||
labels.forEach { (row, s) ->
|
||||
val y = top + row * (cell + gap) + cell * 0.78f
|
||||
canvas.drawText(s, labelW - context.dpf(4f), y, textPaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 项目占比环:中间显示总时长,环上按项目分色。 */
|
||||
class DonutView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
) : View(context, attrs) {
|
||||
|
||||
private var slices: List<ProjectSlice> = emptyList()
|
||||
|
||||
private val arcPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = context.dpf(16f)
|
||||
strokeCap = Paint.Cap.BUTT
|
||||
}
|
||||
private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = context.dpf(16f)
|
||||
color = context.col(R.color.ring_track)
|
||||
}
|
||||
private val valuePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(19f)
|
||||
color = context.col(R.color.title)
|
||||
textAlign = Paint.Align.CENTER
|
||||
isFakeBoldText = true
|
||||
}
|
||||
private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textSize = context.spf(10f)
|
||||
color = context.col(R.color.text_tertiary)
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
fun setSlices(list: List<ProjectSlice>) {
|
||||
slices = list
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** 环中心的说明文字(项目分布 / 任务分布共用这个控件) */
|
||||
var caption: String = ""
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val r = minOf(width, height) / 2f - arcPaint.strokeWidth / 2f - context.dpf(2f)
|
||||
val cx = width / 2f
|
||||
val cy = height / 2f
|
||||
canvas.drawCircle(cx, cy, r, trackPaint)
|
||||
|
||||
val box = RectF(cx - r, cy - r, cx + r, cy + r)
|
||||
val total = slices.sumOf { it.seconds }
|
||||
if (total > 0) {
|
||||
var start = -90f
|
||||
val gapDeg = if (slices.size > 1) 2.4f else 0f
|
||||
slices.forEach { s ->
|
||||
val sweep = s.seconds.toFloat() / total * 360f
|
||||
arcPaint.color = if (s.color == -1) context.col(R.color.text_tertiary) else s.color
|
||||
canvas.drawArc(box, start + gapDeg / 2f, (sweep - gapDeg).coerceAtLeast(0.6f), false, arcPaint)
|
||||
start += sweep
|
||||
}
|
||||
}
|
||||
|
||||
val centerText = if (total <= 0) "0m" else Dates.shortDuration(total)
|
||||
canvas.drawText(centerText, cx, cy + context.dpf(2f), valuePaint)
|
||||
val cap = if (caption.isEmpty()) "总专注" else caption
|
||||
canvas.drawText(cap, cx, cy + context.dpf(18f), labelPaint)
|
||||
}
|
||||
}
|
||||
73
src/main/java/com/focusbox/app/widget/RingView.kt
Normal file
73
src/main/java/com/focusbox/app/widget/RingView.kt
Normal file
@@ -0,0 +1,73 @@
|
||||
package com.focusbox.app.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RectF
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import com.focusbox.app.R
|
||||
import com.focusbox.app.util.col
|
||||
import com.focusbox.app.util.dpf
|
||||
|
||||
/**
|
||||
* 计时圆环。
|
||||
*
|
||||
* 只用一条弧表达进度:从 -90° 顺时针扫过 progress * 360°。
|
||||
* 进度为 0 时不画弧——圆头端点会在起点留下一个圆点,看起来像"已经走了 1%"。
|
||||
*/
|
||||
class RingView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
) : View(context, attrs) {
|
||||
|
||||
var progress: Float = 0f
|
||||
set(value) {
|
||||
field = value.coerceIn(0f, 1f)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
var ringColor: Int = context.col(R.color.brand)
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
var trackColor: Int = context.col(R.color.ring_track)
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
var strokeDp: Float = 12f
|
||||
set(value) {
|
||||
field = value
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
}
|
||||
private val rect = RectF()
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val stroke = context.dpf(strokeDp)
|
||||
paint.strokeWidth = stroke
|
||||
val pad = stroke / 2f + context.dpf(2f)
|
||||
rect.set(pad, pad, width - pad, height - pad)
|
||||
val radius = minOf(rect.width(), rect.height()) / 2f
|
||||
|
||||
paint.color = trackColor
|
||||
canvas.drawCircle(rect.centerX(), rect.centerY(), radius, paint)
|
||||
|
||||
if (progress > 0.002f) {
|
||||
paint.color = ringColor
|
||||
val box = RectF(
|
||||
rect.centerX() - radius, rect.centerY() - radius,
|
||||
rect.centerX() + radius, rect.centerY() + radius,
|
||||
)
|
||||
canvas.drawArc(box, -90f, 360f * progress, false, paint)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user