官网:https://www.echartsjs.com/index.html
参考:https://www.jianshu.com/p/c2b589170379
在官网上我们可以获取我们所需要的js
Android 使用:
上面的依赖是为了使用定义好的etcharts图表中展示的各个js代码节点的属性,设置好后转变为json,然后调用展示,将数据传入,在上面的html代码中会将json转变为option对象,做完上述操作后我们就可以开始定制我们自己的图表了
例子:展示饼图:
首先我们可以在etchar中找到我们需要展示的表:(https://www.echartsjs.com/examples/)选择饼图,选择我们需要展示的样式:
这是我获取到的图表样式,其对应的js:
option = {
title : {
text: '某站点用户访问来源',
subtext: '纯属虚构',
x:'center'
},
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
},
series : [
{
name: '访问来源',
type: 'pie',
radius : '55%',
center: ['50%', '60%'],
data:[
{value:335, name:'直接访问'},
{value:310, name:'邮件营销'},
{value:234, name:'联盟广告'},
{value:135, name:'视频广告'},
{value:1548, name:'搜索引擎'}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
我们也可以在此基础上进行修改js,选择运行,看实现的效果是否是我们需要的效果,当然这需要一定的js开发能力
然后我们就可以在安卓代码上操作了:
1,拿到Webview并做基本的设置
- 下载Echarts。你可以根据你的需求在ECharts官网下载需要的ECharts组件,可以选择完成版或在线定制。
- 将下载好的
echarts.min.js
文件放入工程中assets
目录下。如果没有assets
目录,可以先在mian
目录下,通过右击 new -> Folder -> Assets Folder 创建。 -
依赖EChart java 对象库
注意:因为该对象库依赖Gson,所以project同样需要添加Gson依赖
dependencies { compile 'com.github.abel533:ECharts:3.0.0.2' implementation 'com.google.code.gson:gson:2.8.1' }
- 编写echarts.html文件,并将echarts.html放入assets目录。
<!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>
-
Android 代码:
wv_analysis = (WebView) findViewById(R.id.wv_analysis); wv_analysis.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); WebSettings webSettings = wv_analysis.getSettings(); webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); webSettings.setJavaScriptEnabled(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); webSettings.setAllowFileAccess(false); webSettings.setAllowFileAccessFromFileURLs(false); webSettings.setAllowUniversalAccessFromFileURLs(false); webSettings.setDefaultTextEncodingName("gbk"); webSettings.setSupportZoom(false); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); wv_analysis.removeJavascriptInterface("searchBoxJavaBridge_"); wv_analysis.removeJavascriptInterface("accessibility"); wv_analysis.removeJavascriptInterface("accessibilityTraversal"); wv_analysis.setWebViewClient(new MyWebViewClient()); wv_analysis.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
2.创建WebViewClient:
private class MyWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); refreshLineChart(); } private void refreshLineChart() { //处理数据,调用工具类生成option对象的json数据 Object[] oneData = new Object[paymentAnalyses.size()]; List<Map<String, Object>> twoData = new ArrayList<>(); for (int i = 0; i < paymentAnalyses.size(); i++) { oneData[i] = paymentAnalyses.get(i).getPayMethodName(); Map<String, Object> data = new HashMap<>(); data.put("value", paseFloat(paymentAnalyses.get(i).getPayTotal())); data.put("name", paymentAnalyses.get(i).getPayMethodName()); twoData.add(data); } String optionString = EchartOptionUtil.getBingTuChartOptions(oneData, twoData).toString();//生成json String call = "javascript:loadEcharts('" + optionString + "')"; wv_analysis.loadUrl(call); } /** * shouldInterceptRequest WebView * 中调用的每个请求都会经过该拦截器,如果一个页面有超链接,那么依然会经过该拦截器 * 参数说明: * * @param view 接收WebViewClient的那个实例,前面看到webView.setWebViewClient(new * MyAndroidWebViewClient()),即是这个webview。 * @param url raw url 制定的资源 * @return 返回WebResourceResponse包含数据对象,或者返回null */ @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (url.contains("http") || url.contains("www") || url.contains("https")) { String response = "<html><body>该数据不存在</body></html>"; WebResourceResponse weResourceResponse = new WebResourceResponse( "text/html", "utf-8", new ByteArrayInputStream( response.getBytes())); return weResourceResponse; } else { return super.shouldInterceptRequest(view, url); } } /* * url重定向会执行此方法以及点击页面某些链接也会执行此方法 * 当加载的网页需要重定向的时候就会回调这个函数告知我们应用程序是否需要接管控制网页加载,如果应用程序接管,并且return * true意味着主程序接管网页加载,如果返回false让webview自己处理。 * * @param view 当前webview * * @param url 即将重定向的url * * @return true:表示当前url已经加载完成,即使url还会重定向都不会再进行加载, false * 表示此url默认由系统处理,该重定向还是重定向,直到加载完成 */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("http") || url.contains("www") || url.contains("https")) { return true; } else { return super.shouldOverrideUrlLoading(view, url); } } }
3.创建生成处理数据生成option的工具类:
public class EchartOptionUtil { /** * 饼状图 * * @param data * @param yAxis * @return */ public static GsonOption getBingTuChartOptions(Object[] data, List<Map<String, Object>> yAxis) { GsonOption option = new GsonOption(); option.title("支付方式占比"); option.title().setX(X.center); option.tooltip().trigger(Trigger.item); option.tooltip().formatter("{a} {b}:{c} ({d}%)"); option.legend().left(X.left).orient(Orient.vertical); option.legend().data(data); Pie pie = new Pie(); pie.name(""); pie.type(SeriesType.pie); pie.center("50%", "70%").radius("55%"); pie.itemStyle().emphasis().shadowBlur(10).shadowOffsetX(0).shadowColor("rgba(0, 0, 0, 0.5)"); pie.setData(yAxis); option.series(pie); return option; } /** * 折线和柱状图混合图 * * @return */ public static Map<String, Object> getLineChartOptions( Object[] xAxisData, double yAxisOneMin, double yAxisOneMax, double yAxisOneInterval, double yAxisTwoMin, double yAxisTwoMax, double yAxisTwoMaxInterval, Object[] yAxisOneData, Object[] yAxisTwoData, Object[] yAxisThreeData) { Map<String, Object> option = new HashMap<String, Object>(); Map<String, Object> tooltip = new HashMap<String, Object>(); tooltip.put("trigger", "axis"); Map<String, Object> axisPointer = new HashMap<String, Object>(); axisPointer.put("type", "cross"); Map<String, Object> crossStyle = new HashMap<String, Object>(); crossStyle.put("color", "#999"); axisPointer.put("crossStyle", crossStyle); tooltip.put("axisPointer", axisPointer); option.put("tooltip", tooltip); Map<String, Object> toolbox = new HashMap<String, Object>(); Map<String, Object> feature = new HashMap<String, Object>(); Map<String, Object> dataView = new HashMap<String, Object>(); dataView.put("show", true); dataView.put("readOnly", false); feature.put("dataView", dataView); Map<String, Object> magicType = new HashMap<String, Object>(); magicType.put("show", true); List<String> type = new ArrayList<String>(); type.add("line"); type.add("bar"); magicType.put("type", type); feature.put("magicType", magicType); Map<String, Object> restore = new HashMap<String, Object>(); restore.put("show", true); feature.put("restore", restore); Map<String, Object> saveAsImage = new HashMap<String, Object>(); saveAsImage.put("show", true); feature.put("saveAsImage", saveAsImage); toolbox.put("feature", feature); option.put("toolbox", toolbox); Map<String, Object> legend = new HashMap<String, Object>(); legend.put("data", new Object[]{"月销售额", "日均销售额", "毛利率"}); option.put("legend", legend); List<Map<String, Object>> xAsis = new ArrayList<Map<String, Object>>(); Map<String, Object> xAsisMap = new HashMap<String, Object>(); xAsisMap.put("type", "category"); xAsisMap.put("data", xAxisData); Map<String, Object> axisPointers = new HashMap<String, Object>(); axisPointers.put("type", "shadow"); xAsisMap.put("axisPointer", axisPointers); xAsis.add(xAsisMap); option.put("xAxis", xAsis); List<Map<String, Object>> yAsis = new ArrayList<Map<String, Object>>(); Map<String, Object> yAsisOne = new HashMap<String, Object>(); yAsisOne.put("type", "value"); yAsisOne.put("name", "销售额"); yAsisOne.put("min", yAxisOneMin); yAsisOne.put("max", yAxisOneMax); yAsisOne.put("interval", yAxisOneInterval); Map<String, Object> axisLabel = new HashMap<String, Object>(); axisLabel.put("formatter", "{value}"); yAsisOne.put("axisLabel", axisLabel); yAsis.add(yAsisOne); Map<String, Object> yAsisTwo = new HashMap<String, Object>(); yAsisTwo.put("type", "value"); yAsisTwo.put("name", "毛利率"); yAsisTwo.put("min", yAxisTwoMin); yAsisTwo.put("max", yAxisTwoMax); yAsisTwo.put("interval", yAxisTwoMaxInterval); Map<String, Object> axisLabelTwo = new HashMap<String, Object>(); axisLabelTwo.put("formatter", "{value}"); yAsisTwo.put("axisLabel", axisLabel); yAsis.add(yAsisTwo); option.put("yAxis", yAsis); List<Map<String, Object>> series = new ArrayList<Map<String, Object>>(); Map<String, Object> seriesOne = new HashMap<String, Object>(); seriesOne.put("name", "月销售额"); seriesOne.put("type", "bar"); seriesOne.put("data", yAxisOneData); series.add(seriesOne); Map<String, Object> seriesTwo = new HashMap<String, Object>(); seriesTwo.put("name", "日均销售额"); seriesTwo.put("type", "bar"); seriesTwo.put("data", yAxisTwoData); series.add(seriesTwo); Map<String, Object> seriesThree = new HashMap<String, Object>(); seriesThree.put("name", "毛利率"); seriesThree.put("type", "line"); seriesThree.put("yAxisIndex", 1); seriesThree.put("data", yAxisThreeData); series.add(seriesThree); option.put("series", series); return option; } } 上述就是调用传参到js的调用,我这使用的使用getBingTuChartOptions,这个中的option的各个节点都有定义,可以直接生成对象使用,而另一个方法是自己按照js的节点通过map对象一点一点加的比较麻烦,但同样是转变为js中option的json数据,同样可以使用。 我们可以将获取到的json放到echarts中运行看是否生成我们需要的图表,如果有错误再调整echarts合适后再调我们的实体类对象,一点一点调整。 4.加载网页 wv_analysis.loadUrl("file:///android_asset/echarts.html");