android - 使用 mpandroidchart 和 kotlin 显示条形图

标签 android kotlin mpandroidchart

我正在尝试使用 Kotlin 使用 mpandroidchart 库显示一个简单的条形图。我在网上找到的大多数示例都是使用 java 的,所以复制代码,粘贴到 android studio 中以转换为 Kotlin,然后尝试修复错误是必要的。
但我似乎无法修复使用 BarEntry 时出现的问题,如图所示。
任何帮助表示赞赏。谢谢

enter image description here

最佳答案

enter image description here
步骤1:

dependencies {

implementation 'com.github.PhilJay:MPAndroidChart:v2.2.4' 
}
第2步:
repositories {

maven { url "https://jitpack.io" }
}
第 3 步:
    class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setBarChart()
    }

    private fun setBarChart() {
        val entries = ArrayList<BarEntry>()
        entries.add(BarEntry(8f, 0))
        entries.add(BarEntry(2f, 1))
        entries.add(BarEntry(5f, 2))
        entries.add(BarEntry(20f, 3))
        entries.add(BarEntry(15f, 4))
        entries.add(BarEntry(19f, 5))

        val barDataSet = BarDataSet(entries, "Cells")

        val labels = ArrayList<String>()
        labels.add("18-Jan")
        labels.add("19-Jan")
        labels.add("20-Jan")
        labels.add("21-Jan")
        labels.add("22-Jan")
        labels.add("23-Jan")
        val data = BarData(labels, barDataSet)
        barChart.data = data // set the data and list of lables into chart

        barChart.setDescription("Set Bar Chart Description")  // set the description

        //barDataSet.setColors(ColorTemplate.COLORFUL_COLORS)
        barDataSet.color = resources.getColor(R.color.colorAccent)

        barChart.animateY(5000)
    }
}
第4步 :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.github.mikephil.charting.charts.BarChart
    android:id="@+id/barChart"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 </androidx.constraintlayout.widget.ConstraintLayout>

关于android - 使用 mpandroidchart 和 kotlin 显示条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59854223/

相关文章:

android - sharedpreferences 帮助程序类上的 nullPointerException 运行测试时

java - 删除 MPAndroidChart 中的 BarDataSet

android - Gps 位置为空

android - 在android中自动启动/播放视频

maven - 使用 maven 时,Kotlin 未从 src/main/kotlin 编译

java - 简单XML : ConstructorException

android - XAxis 标签在 MPAndroidChart 中绘制不正确

android - 使用 MPAndroidChart 自定义 XAxis 标签

java - android 中的导航选项卡在膨胀菜单时出现 ABS nullpointerexception

android - Xamarin Forms 跨平台 BBCode 支持