Search code examples
androidkotlinanychart

Anychart create graph using function as parameter


I have this function with which I create AnyChart Graph. I want to make a lot of functions, for different graphs, like this one, and also to show them into different MaterialDialogs.

        private fun createChart(): Cartesian {
            val cartesian: Cartesian = AnyChart.cartesian(
            (...)
            return cartesian
        }

For this task, I made a general function, which will be called with the specific views IDs and specific function for creating the graph

private fun showDialog(layoutId : Int , chartId : Int, function: (Chart)) {

        val dialog = MaterialDialog(requireContext())
            .customView(layoutId)
            .cornerRadius(5.5f)

        val chartView: AnyChartView = dialog.findViewById(chartId)
        APIlib.getInstance().setActiveAnyChartView(chartView)
        chartView.setDebug(true)

        chartView.setChart(function) // <------ The problem is here
        //chartView.setChart(createChart() works fine 
        dialog.show()
    }

I will call this function at onClick listener of some view and specify which chart to be shown and which draw function to be used

private fun showWeatherDialog() {
        showDialog(R.layout.activity_graph_test,R.id.any_chart_view,createChart())
}

If I use the normal function call, the graph is drawn normally, but when I call the function parameter it doesn't work

   chartView.setChart(function) // <------ The problem is here
   //chartView.setChart(createChart() works fine

The error from Anychart:

E/AnyChart: Uncaught ReferenceError: cartesian43 is not defined


Solution

  • Here is my solution:

        private fun showWeatherDialog() {
            showDialog(R.layout.activity_graph_test, R.id.any_chart_view) { createChart() }
        }
    
        private fun showDialog(layoutId: Int, chartId: Int, drawingChart: (()-> Cartesian)) {
             (...)
            chartView.setChart(drawingChart.invoke())
            dialog.show()
        }