Android ECharts折线、圆柱、饼状初步实现

做Android开发经常会需要画一些图表,ECharts就是很好用的一款第三方的框架

Android ECharts折线、圆柱、饼状初步实现

1、配置ECharts

Android ECharts折线、圆柱、饼状初步实现

echarts.min.js文件就需要你自己去下载啦,可以直接选择:

Android ECharts折线、圆柱、饼状初步实现

echart.html:

<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8">
    </head>
    <body style="height: 100%; margin: 0">
        <div id="container" style="height: 100%"></div>
        <script type="text/javascript" src="./echarts.min.js"></script>
        <script type="text/javascript">
            var dom =document.getElementById("container");
            var myChart =echarts.init(dom);
            var app ={};
            function loadEcharts(echartJson){
                var option = JSON.parse(echartJson);
                if (option &&typeof option ==="object") {
                    myChart.setOption(option,true);
                }
            }
        </script>
    </body>
</html>

2、添加依赖

    implementation 'com.github.abel533:ECharts:3.0.0.2'
    implementation 'com.google.code.gson:gson:2.8.6'

3、因为Echarts需要在WebView中显示,所以我们直接自定义一个EchartView继承自WebView用来显示图表。

public class EchartView extends WebView {
    private static final String TAG = EchartView.class.getSimpleName();

    public EchartView(Context context) {
        this(context, null);
    }

    public EchartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EchartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);
        loadUrl("file:///android_asset/echarts.html");
    }

    /**刷新图表
     * java调用js的loadEcharts方法刷新echart
     * 不能在第一时间就用此方法来显示图表,因为第一时间html的标签还未加载完成,不能获取到标签值
     * @param option
     */
    public void refreshEchartsWithOption(GsonOption option) {
        if (option == null) {
            return;
        }
        String optionString = option.toString();
        String call = "javascript:loadEcharts('" + optionString + "')";
        loadUrl(call);
    }
}

4、EchartOptionUtil工具类,简单封装了折线圆柱饼状,更多图表的封装请参照EChart java 对象库ECharts官方例子

public class EchartOptionUtil {

    //折线图
    public static GsonOption getLineChartOptions(Object[] xAxis, Object[] yAxis, Object[] yAxis2) {
        GsonOption option = new GsonOption();
        option.title("折线图");
        option.legend("销量");
        option.legend("销量2");
        option.tooltip().trigger(Trigger.axis);

        ValueAxis valueAxis = new ValueAxis();
        option.yAxis(valueAxis);

        CategoryAxis categorxAxis = new CategoryAxis();
        categorxAxis.axisLine().onZero(false);
        categorxAxis.boundaryGap(true);
        categorxAxis.data(xAxis);
        option.xAxis(categorxAxis);

        Line line = new Line();
        line.smooth(false).name("销量").data(yAxis).itemStyle().normal().lineStyle().shadowColor("rgba(0,0,0,0.4)");
        Line line1 = new Line();
        line1.smooth(false).name("销量2").data(yAxis2).itemStyle().normal().lineStyle().shadowColor("rgba(6,6,6,0.4)");
        option.series(line,line1);
        return option;
    }

    public static  GsonOption getBarChartOptions(Object[] xAxis, Object[] yAxis){
        GsonOption option = new GsonOption();
        option.title("柱状图");
        option.legend("销量");

        ValueAxis valueAxis = new ValueAxis();
        option.yAxis(valueAxis);
        CategoryAxis categorxAxis = new CategoryAxis();
        categorxAxis.axisLine().onZero(false);
        categorxAxis.boundaryGap(true);
        categorxAxis.data(xAxis);
        option.xAxis(categorxAxis);

        Bar bar = new Bar();
        bar.name("销量").data(yAxis).itemStyle().normal().setBarBorderColor("rgba(0,0,0,0.4)");
        option.series(bar);
        return option;
    }
    public static  GsonOption getPieChartOptions(){
        GsonOption option = new GsonOption();
        option.title("圆饼图");
        option.legend("陕西");
        option.legend("陕西2");
        option.legend("陕西3");
        option.tooltip().trigger(Trigger.item);

        Pie pie = new Pie();
        HashMap hashMap = new HashMap();
        hashMap.put("value",50);
        hashMap.put("name","陕西");
        HashMap hashMap1 = new HashMap();
        hashMap1.put("value",30);
        hashMap1.put("name","陕西2");
        HashMap hashMap2 = new HashMap();
        hashMap2.put("value",20);
        hashMap2.put("name","陕西3");
        pie.radius(60).data(hashMap,hashMap1,hashMap2);
        option.series(pie);
        return option;
    }
}

5、activity_main布局

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.example.echartdemo.EchartView
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"/>
    <com.example.echartdemo.EchartView
        android:id="@+id/barChart"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>
    <com.example.echartdemo.EchartView
        android:id="@+id/pieChart"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>

</LinearLayout>

6、MainActivity主页面使用

public class MainActivity extends AppCompatActivity {

    private EchartView lineChart;
    private EchartView barChart;
    private EchartView pieChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        lineChart = findViewById(R.id.lineChart);
        barChart = findViewById(R.id.barChart);
        pieChart = findViewById(R.id.pieChart);
        lineChart.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //最好在h5页面加载完毕后再加载数据,防止html的标签还未加载完成,不能正常显示
                refreshLineChart();
            }
        });
        barChart.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //最好在h5页面加载完毕后再加载数据,防止html的标签还未加载完成,不能正常显示
                refreshBarChart();
            }
        });
        pieChart.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //最好在h5页面加载完毕后再加载数据,防止html的标签还未加载完成,不能正常显示
                refreshPieChart();
            }
        });
    }

    private void refreshPieChart() {
        pieChart.refreshEchartsWithOption(EchartOptionUtil.getPieChartOptions());

    }

    private void refreshBarChart() {
        Object[] x = new Object[]{
                "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
        };
        Object[] y = new Object[]{
                820, 932, 901, 934, 1290, 1330, 1320
        };
        barChart.refreshEchartsWithOption(EchartOptionUtil.getBarChartOptions(x, y));
    }

    private void refreshLineChart() {
        Object[] x = new Object[]{
                "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
        };

        Object[] y = new Object[]{
                820, 932, 901, 934, 1290, 1330, 1320
        };
        Object[] y2 = new Object[]{
                420, 532, 601, 734, 890, 530, 1020
        };
        lineChart.refreshEchartsWithOption(EchartOptionUtil.getLineChartOptions(x, y,y2));
    }
}