【问题标题】:Add x axis as datetime label in MPAndroidChart? (Kotlin)在 MPAndroidChart 中添加 x 轴作为日期时间标签? (科特林)
【发布时间】:2021-04-07 20:16:02
【问题描述】:

我相信this question and answer 解释了如何在 Java 中将时间序列数据格式化为可读的日期标签。你如何在 Kotlin 中做同样的事情?

【问题讨论】:

    标签: android kotlin mpandroidchart


    【解决方案1】:

    您可以创建一个自定义格式化程序类扩展 IAxisValueFormatter:

    class MyCustomFormatter() : IAxisValueFormatter 
    {
        override fun getFormattedValue(value: Float, axis: AxisBase?): String
        {   
            val dateInMillis = value.toLong()
            val date = Calendar.getInstance().apply {
                timeInMillis = dateInMillis
            }.time
    
            return SimpleDateFormat("dd MMM", Locale.getDefault()).format(date)
        }
    }
    

    然后将其分配给您的图表

        chart?.xAxis?.valueFormatter = MyCustomFormatter()
    

    【讨论】:

    • 谢谢,这帮助我走上了正轨。我不得不从另一个答案更新代码,因为它不反映最新版本的 MPAndroidChart
    【解决方案2】:

    使用 MPAndroidChart 3.0+ 版本:

    将格式化程序设置为 x 轴:

    // Formatter to adjust epoch time to readable date
    lineChart.xAxis.valueFormatter = LineChartXAxisValueFormatter()
    

    新建一个 LineChartXAxisValueFormatter 类:

    class LineChartXAxisValueFormatter : IndexAxisValueFormatter() {
    
        override fun getFormattedValue(value: Float): String? {
        // Convert float value to date string
        // Convert from seconds back to milliseconds to format time  to show to the user
        val emissionsMilliSince1970Time = value.toLong() * 1000
    
        // Show time in local version
        val timeMilliseconds = Date(emissionsMilliSince1970Time)
        val dateTimeFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
        return dateTimeFormat.format(timeMilliseconds)
      }
    }
    

    将条目添加到 ChartDataArray 时,它们以秒而不是毫秒为单位添加,以避免输入为浮点数(即毫秒除以 1000)的潜在精度问题。

    chartDataArray.add(Entry(secondsSince1970.toFloat(), yValue.toFloat()))
    

    编码愉快!

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 2017-04-09
      • 2017-10-13
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2022-06-30
      相关资源
      最近更新 更多