导入 v0.1.0 / v0.2.0 源码:五模块首版、交互重构、重复任务、任务分布

- 源码镜像 src/main(81 个文件):首页双模式、任务、项目、统计、设置
- 补齐 README / LICENSE / CHANGELOG / CONTRIBUTING / .gitignore
- 不含构建配置、签名材料、编译产物与备份数据
This commit is contained in:
XIGE
2026-11-28 00:25:22 +08:00
parent f87c29f232
commit d52deeff5e
85 changed files with 6215 additions and 1 deletions

View 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()
}
}
}
}

View 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)
}
}

File diff suppressed because it is too large Load Diff

View 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
}
}
}
}

View 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)
}
}
}

View 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()
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View 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
}
}

View 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()
}
}

View 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()
}
}