See for more examples:Echarts.baidu.com/examples.ht…

preface

Use baidu Echart framework: echarts.baidu.com/ gitee.com/free/EChart… See iOS encapsulation implementation: github.com/Pluto-Y/iOS… And other information on the implementation of the Android version of the simple packaging time is not very abundant, can only be in fragmentary time to supplement bit by bit, so there will certainly be many deficiencies hope in the future one day they can be packaged very perfect

Project GitHub address TAndroidEChart

Add dependencies:

  • Methods a
Step 1: Add maven {url'[https://jitpack.io](https://jitpack.io/)' } 到project的build.gradle     
allprojects {
     repositories {
          ...
          maven { url '[https://jitpack.io](https://jitpack.io/)'}} versionNum is the value of the latest version, for example, v1.2.1. Step 2: Add compile'com.github.tikeyc:TAndroidEChart:versionNum'Go to build. Gradle Dependencies {compile'com.github.tikeyc:TAndroidEChart:versionNum'
}
Copy the code
  • Import a module: TAndroidechartLibrary

How to use:

xml:
<com.tikeyc.tandroidechartlibrary.TEChartWebView
        android:id="@+id/barChartWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.tikeyc.tandroidechartlibrary.TEChartWebView>
Copy the code
Specific code:
If you need to refresh the chart later, you can call it this way (note: Barchartwebview.refreshechartswithoption (getLineAndBarChartOption()));Copy the code
public class TBarChartActivity extends TBaseActivity {

    @ViewInject(R.id.barChartWebView)
    private TEChartWebView barChartWebView;

    @Event(R.id.navigationBar_title_tv)
    private void titleClick(View view) {
        if(! view.isSelected()) { barChartWebView.refreshEchartsWithOption(getLineChartOptions()); }else{ barChartWebView.refreshEchartsWithOption(getLineAndBarChartOption()); } view.setSelected(! view.isSelected()); } @Override protected void onCreate(Bundle savedInstanceState) { this.isLandScape =true; super.onCreate(savedInstanceState); // Set landscapeif(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        setContentView(R.layout.activity_tbar_chart);

        initData();

        initView();
    }



    private void initData() {

    }


    private void initView() {
        x.view().inject(this);

        //
        //navigationBar_title_tv.setText("BarChart"); // Enable debug mode by defaultfalse
        barChartWebView.setDebug(true); / / set up the data source barChartWebView. SetDataSource (new TEChartWebView.DataSource() {
            @Override
            public GsonOption markChartOptions() {
                returngetLineAndBarChartOption(); }}); / / add event listeners TEChartConstant. PYEchartAction [] echartActions = {TEChartConstant. PYEchartAction. PYEchartActionLegendSelected, TEChartConstant.PYEchartAction.PYEchartActionClick}; barChartWebView.addEchartActionHandler(echartActions, new TEChartWebView.OnAddEchartActionHandlerResponseResultListener() {@ Override public void actionHandlerResponseResult (String result) {/ / view information processing events /*TEChartConstant.PYEchartAction.PYEchartActionLegendSelected * *{"selected": {"Evaporation":true."Precipitation":true."Average temperature":true},"target":"Evaporation"."type":"legendSelected"."event": {"zrenderX": 220.33299255371094."zrenderY": 8.666999816894531."zrenderFixed": 1}."__echartsId":1512031135165}
                 */


                /*TEChartConstant.PYEchartAction.PYEchartActionClick
                 *
                 *{"seriesIndex": 1,"seriesName":"Precipitation"."dataIndex": 4."data": 28.7."name":"May"."value": 28.7."type":"click"."event": {"zrenderX": 261,"zrenderY": 209,"zrenderFixed": * / 1}}}}); } / according to https://mvnrepository.com/artifact/com.github.abel533/ECharts * * * * http://echarts.baidu.com/examples.html official instance Configure json data * @return
     */
    public GsonOption getLineAndBarChartOption() {
        //http://echarts.baidu.com/echarts2/doc/example/mix1.html
        GsonOption option = new GsonOption();
        //title
        String text = "text";
        String subText = "subText";
        option.title(text,subText);
        //tooltip
        Tooltip tooltip = new Tooltip();
        tooltip.trigger(Trigger.axis);
        option.tooltip(tooltip);
        //toolbox
        Toolbox toolbox = new Toolbox();
        toolbox.show(true);
        Map<String, Feature> feature = new HashMap<String, Feature>();
        feature.put("mark",new Feature().show(true));
        feature.put("dataView",new DataView().show(true).readOnly(false));
        feature.put("magicType",new MagicType(Magic.line, Magic.bar).show(true));
        feature.put("restore",new Restore().show(true));
        feature.put("saveAsImage",new SaveAsImage().show(false));
        toolbox.setFeature(feature);
        option.toolbox(toolbox);
        //calculable
        option.setCalculable(true);
        //legend
        String legend1 = "Evaporation";
        String legend2 = "Precipitation";
        String legend3 = "Average temperature";
        Legend legend = new Legend();
        legend.data(legend1,legend2,legend3);
        option.legend(legend);
        //grid
//            Grid grid = new Grid();
//            grid.y2(80);
//            option.grid(grid);
        //xAxis
        List<Axis> xAxis = new ArrayList<Axis>();
        CategoryAxis categoryAxis = new CategoryAxis();
        {
            List xAxisValues = new ArrayList();
            for (int i = 1; i <= 12; i++) {
                xAxisValues.add(i + "Month");
            }
            categoryAxis.setData(xAxisValues);
        }
        xAxis.add(categoryAxis);
        option.xAxis(xAxis);
        //yAxis
        List<Axis> yAxis = new ArrayList<Axis>();
        {
            ValueAxis valueAxis = new ValueAxis();
            valueAxis.name("Water");
            valueAxis.axisLabel(new AxisLabel().formatter("{value} ml"));
            yAxis.add(valueAxis);
        }
        {
            ValueAxis valueAxis = new ValueAxis();
            valueAxis.name("Temperature");
            valueAxis.axisLabel(new AxisLabel().formatter("{value} ° C")); yAxis.add(valueAxis); } option.yAxis(yAxis); //series List<Series> series = new ArrayList<Series>(); { Bar bar = new Bar(); bar.name(legend1).type(SeriesType.bar).yAxisIndex(0); List data = new ArrayList(); Double arrays [] = {2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3};for(double value : arrays){ data.add(value); } bar.setData(data); series.add(bar); } { Bar bar = new Bar(); bar.name(legend2).type(SeriesType.bar).yAxisIndex(0); List data = new ArrayList(); Double arrays [] = {2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3};for(double value : arrays){ data.add(value); } bar.setData(data); series.add(bar); } { Line line = new Line(); line.name(legend3).type(SeriesType.line).yAxisIndex(1); List data = new ArrayList(); Double arrays [] = {2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2};for (double value : arrays){
                data.add(value);
            }
            line.setData(data);
            series.add(line);
        }
        option.series(series);
        //
        return option;
    }


    public GsonOption getLineChartOptions() {/ / address: http://echarts.baidu.com/echarts2/doc/example/line5.html GsonOption option = new GsonOption (); option.legend("Relationship between altitude (km) and temperature (°C)");

        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);

        option.calculable(true);
        option.tooltip().trigger(Trigger.axis).formatter(Temperature: 

{b}km: {c}°C"
); ValueAxis valueAxis = new ValueAxis(); valueAxis.axisLabel().formatter("{value} ° C"); option.xAxis(valueAxis); CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.axisLine().onZero(false); categoryAxis.axisLabel().formatter("{value} km"); categoryAxis.boundaryGap(false); categoryAxis.data(0, 10, 20, 30, 40, 50, 60, 70, 80); option.yAxis(categoryAxis); Line line = new Line(); line.smooth(true).name("Relationship between altitude (km) and temperature (°C)"). The data (15 to 50, 56.5, 46.5, 22.1, 2.5, 27.7, 55.7, 76.5). The itemStyle (). The normal () graphics.linestyle (.) shadowColor ("Rgba (0,0,0,0.4)"); option.series(line); returnoption; }}Copy the code

Package source code:

TEChartWebView control source code
Public class extends WebView {/** defaultfalse* Called multiple times in echart. HTML and echart.js for developmentfunctionToast (MSG) can be set totrueEnable debug */ private Boolean isDebug =false; /** * store the first time Android calls JSfunction* Because echart. HTML and echart. js have not been loaded for the first time, while the Java code is called at the first time * so we need to wait until the HTML tag and JS load successfully before calling. In the WebViewClient onPageFinished method * / private a List < String > shouldCallJsFunctionArray = new ArrayList < String > (); public voidsetDebug(boolean isDebug) {
        this.isDebug = isDebug;
    }

    public boolean isDebug() {

        return isDebug;
    }

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

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

    public TEChartWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initWebViewClient();

        init();
    }

    private void init() {
        //
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);
        addJavascriptInterface(new TEChartWebView.WebAppEChartInterface(getContext()), "Android");
        loadUrl("file:///android_asset/echartWeb/EChart/EChart.html");
    }

    private void initWebViewClient () {
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                for(String callJs : shouldCallJsFunctionArray) { loadUrl(callJs); } } @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); }}); * * * Java calls refresh chart} / js refresh every * refreshEChartWithGsonOption method can't use this method to display the chart in the first time, because the first HTML tags are not loaded, @param option */ public void refreshEchartsWithOption(GsonOption) {if (dataSource == null) {
            assert false : "ataSource == null";
        }
        String optionString = option.toString();
        String call = "javascript:refreshEchartsWithOption('" + optionString + "')"; loadUrl(call); } / listening to * * * add chart incident response @ param echartActions event name * @ param array onAddEchartActionHandlerResponseResultListener Click after every return events information (every returned event information: http://echarts.baidu.com/api.html#events) response listens to the developer
     */
    public void addEchartActionHandler(TEChartConstant.PYEchartAction[] echartActions, OnAddEchartActionHandlerResponseResultListener onAddEchartActionHandlerResponseResultListener) {
        this.onAddEchartActionHandlerResponseResultListener = onAddEchartActionHandlerResponseResultListener;
        //
        for (TEChartConstant.PYEchartAction echartAction : echartActions) {
            String callString = echartAction.actionValue;
            String call = "javascript:addEchartActionHandler('" + callString + "')"; //loadUrl(call); shouldCallJsFunctionArray.add(call); }} / listening to * * * remove chart incident response @ param echartAction event name * / public void removeEchartActionHandler (TEChartConstant PYEchartAction echartAction) { String callString = echartAction.actionValue; String call ="javascript:removeEchartActionHandler('" + callString + "')"; loadUrl(call); } /** * Display Echart default Loading */ public voidmyChartShowLoading() {
        String call = "javascript:myChartShowLoading()"; //loadUrl(call); shouldCallJsFunctionArray.add(call); } /** * hide Echart's default Loading */ public voidmyChartHideLoading() {
        String call = "javascript:myChartHideLoading()"; loadUrl(call); } / / / / / / / / / / / / / / / / / / / / / / / WebAppEChartInterface / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / * * * js with Android native interaction interface * / class WebAppEChartInterface { Context context; public WebAppEChartInterface(Context context) { this.context = context; } @JavascriptInterface public void showDebugMessage(String message) {if(isDebug) LogUtils.e(message); } /** * get the chart configuration JSON data ** @return
         */
        @JavascriptInterface
        public String getChartOptions() {
            if(dataSource ! = null) { GsonOption option = dataSource.markChartOptions(); LogUtils.d(option.toString());return option.toString();
            }
            returnnull; } / listening to * * * add chart incident response @ param params every returned event information http://echarts.baidu.com/api.html#events
         */
        @JavascriptInterface
        public void addEchartActionHandlerResponseResult(String params) {
            LogUtils.e(params);
            if(onAddEchartActionHandlerResponseResultListener ! = null) { onAddEchartActionHandlerResponseResultListener.actionHandlerResponseResult(params); }} / listening to * * * remove chart incident response @ param params every returned event information http://echarts.baidu.com/api.html#events*/ @JavascriptInterface public void removeEchartActionHandlerResponseResult(String params) { LogUtils.e(params); }} / / / / / / / / / / / / / / / / / / / / / / / WebAppEChartInterface / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / the data source Chart for JSON configuration / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / private DataSource DataSource. public voidsetDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        //
        reload();
    }

    public DataSource getDataSource() {

        returndataSource; } public interface DataSource { GsonOption markChartOptions(); } / / / / / / / / / / / / / / / / / / / / / / / / / / / / the data source for JSON configuration chart / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / add event to monitor every return Event correlation properties (is a json), will return to give developers use the json / / / / / / / / / / / / / / / / / / / / / / / / / / / every returned event information: http://echarts.baidu.com/api.html#events

    private OnAddEchartActionHandlerResponseResultListener onAddEchartActionHandlerResponseResultListener;

    public void setOnAddEchartActionHandlerResponseResultListener(OnAddEchartActionHandlerResponseResultListener onAddEchartActionHandlerResponseResultListener) {
        this.onAddEchartActionHandlerResponseResultListener = onAddEchartActionHandlerResponseResultListener;
    }

    public OnAddEchartActionHandlerResponseResultListener getOnAddEchartActionHandlerResponseResultListener() {

        returnonAddEchartActionHandlerResponseResultListener; } public interface OnAddEchartActionHandlerResponseResultListener { void actionHandlerResponseResult(String result); }}Copy the code

I don’t have enough time, so I can only supplement it bit by bit in my spare time. Therefore, I am sure there will be many deficiencies. I hope I can encapsulate them perfectly one day in the future

Project making address https://github.com/tikeyc/TAndroidEChart