MPAndroidChart LineChart X轴标签显示问题

来源:互联网 发布:淘宝商城cma检测 编辑:程序博客网 时间:2024/06/05 16:56

新接手的项目中用到了MPAndroidChart,有一个BUG,X轴显示的标签(X轴的粒度为5分钟)不是想要的形式,如下图:


将xAxis.setLabelCount(7);替换为xAxis.setLabelCount(7,true);解决,如下图:


第2个重载方法的第二个参数是指强制绘制指定个数的标签,但是可能会造成绘制出现偏差,然后果然出现了,将图表放大出标签和图表对应不上:


采用给linechart注册手势监听,监听缩放状态解决:

//给折线图表注册手势监听,用于监听缩放状态            lineChart.setOnChartGestureListener(new OnChartGestureListener() {//                boolean isForceXAxisLabelCount=true;                boolean isZoomInMax;//初始化变量保存是否已经放大到最大值                @Override                public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {//                    Log.i("zoom","onChartGestureStart: "+lastPerformedGesture.toString());                    isZoomInMax=true;//手势激活的时候将设为true                }                @Override                public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {//                    Log.i("zoom","onChartGestureEnd: "+lastPerformedGesture.toString());                    /**                     * 因为将图标放大到最大值的时候进行放大手势只会执行onChartGestureStart()和onChartGestureEnd(),所以判断isZoomInMax是否还为true,                     * 如果还为true且手势为X轴缩放,将标签设置为强制绘制,保证标签显示的正确性                     */                    if (isZoomInMax && (lastPerformedGesture==ChartTouchListener.ChartGesture.X_ZOOM)){                        xAxis.setLabelCount(7,true);//                        Log.i("zoom","xAxis.setLabelCount(7,true);");                    }                }                @Override                public void onChartLongPressed(MotionEvent me) {                }                @Override                public void onChartDoubleTapped(MotionEvent me) {                    //双击放大了图表                    isZoomInMax=false;                    xAxis.setLabelCount(7);//将强制绘制取消//                    Log.i("zoom","xAxis.setLabelCount(7);");                }                @Override                public void onChartSingleTapped(MotionEvent me) {                }                @Override                public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {                }                @Override                public void onChartScale(MotionEvent me, float scaleX, float scaleY) {//                    Log.i("zoom",scaleX+"|"+scaleY);                    //对图表进行了缩放                    isZoomInMax=false;//对图表进行了缩放                    xAxis.setLabelCount(7);//将强制绘制取消//                    Log.i("zoom","xAxis.setLabelCount(7);");                }                @Override                public void onChartTranslate(MotionEvent me, float dX, float dY) {                }            });

以前从来没有使用过MPAndroidChart,遇到该问题得时候去网上找了一遍没找到解决方法,自己时间仓促,想出此方法,如果有更好的方法,欢迎指出!