Android图表库MPAndroidChart(五)——自定义MarkerView实现选中高亮
在学习本课程之前我建议先把我之前的博客看完,这样对整体的流程有一个大致的了解
- Android图表库MPAndroidChart(一)——了解他的本质,方能得心应手
- Android图表库MPAndroidChart(二)——线形图的方方面面,看完你会回来感谢我的
- Android图表库MPAndroidChart(三)——双重轴线形图的实现,这次就so easy了
- Android图表库MPAndroidChart(四)——条形图的绘制过程过程,隐隐约约我看到了套路
- Android图表库MPAndroidChart(五)——自定义MarkerView实现选中高亮
相信看了上篇的同学会奇怪这个效果

这个高亮显示是怎么来的,这里也提及一下,和百度的覆盖物类似,都是需要自己去写的,所有这里我就自定义了一个
XYMarkerView
public class XYMarkerView extends MarkerView {
    private TextView tvContent;
    private IAxisValueFormatter xAxisValueFormatter;
    private DecimalFormat format;
    public XYMarkerView(Context context, IAxisValueFormatter xAxisValueFormatter) {
        super(context, R.layout.custom_marker_view);
        this.xAxisValueFormatter = xAxisValueFormatter;
        tvContent = (TextView) findViewById(R.id.tvContent);
        format = new DecimalFormat("###.0");
    }
    //回调函数每次MarkerView重绘,可以用来更新内容(用户界面)
    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        tvContent.setText("x: " + xAxisValueFormatter.getFormattedValue(e.getX(), null) + ", y: " + format.format(e.getY()));
        super.refreshContent(e, highlight);
    }
    @Override
    public MPPointF getOffset() {
        return new MPPointF(-(getWidth() / 2), -getHeight());
    }
}
里面有一个自定义的布局
custom_marker_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:background="@drawable/marker">
    <TextView
        android:id="@+id/tvContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="7dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@android:color/white"
        android:textSize="12dp"/>
</RelativeLayout>
其实里面就一个TextView而已,如果你想添加其他什么属性,自己添加就好了
自定义完成之后怎么使用呢?非常的简单哦
//设置悬浮
        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(mBarChart);
        mBarChart.setMarker(mv);
直接设置进去就可以了,这里也只是稍微的提及
有兴趣的加群:555974449










