feat: 为饼图添加点击事件

1. 为CategoryPieChart添加点击事件处理
2. 点击饼图可跳转到对应类别详情页面
This commit is contained in:
yovinchen 2024-11-28 14:34:24 +08:00
parent 8339d3d5da
commit f134304646
2 changed files with 38 additions and 13 deletions

View File

@ -12,16 +12,20 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.ColorTemplate
@Composable
fun CategoryPieChart(
categoryData: List<Pair<String, Float>>,
modifier: Modifier = Modifier
modifier: Modifier = Modifier,
onCategoryClick: (String) -> Unit = {}
) {
val isDarkTheme = isSystemInDarkTheme()
val textColor = MaterialTheme.colorScheme.onSurface.toArgb()
@ -50,6 +54,21 @@ fun CategoryPieChart(
// 设置中心文字颜色跟随主题
setCenterTextColor(textColor)
// 添加点击事件监听器
setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
override fun onValueSelected(e: Entry?, h: Highlight?) {
e?.let {
if (it is PieEntry) {
onCategoryClick(it.label ?: return)
}
}
}
override fun onNothingSelected() {
// 不需要处理
}
})
}
},
update = { chart ->

View File

@ -70,22 +70,28 @@ fun AnalysisScreen(
}
}
// 饼图
// 使用LazyColumn包含饼图和列表
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp)
) {
// 添加饼图作为第一个项目
if (selectedAnalysisType != AnalysisType.TREND) {
item {
CategoryPieChart(
categoryData = categoryStats.map { Pair(it.category, it.percentage.toFloat()) },
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(16.dp)
.padding(bottom = 16.dp),
onCategoryClick = { category ->
onNavigateToCategoryDetail(category, selectedMonth)
}
)
}
}
// 分类统计列表
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp)
) {
// 添加分类统计列表项目
items(categoryStats) { stat ->
CategoryStatItem(
stat = stat,