Android图表库MPAndroidChart(五)——自定义MarkerView实现选中高亮

时间:2023-03-09 19:10:06
Android图表库MPAndroidChart(五)——自定义MarkerView实现选中高亮

Android图表库MPAndroidChart(五)——自定义MarkerView实现选中高亮


在学习本课程之前我建议先把我之前的博客看完,这样对整体的流程有一个大致的了解

相信看了上篇的同学会奇怪这个效果

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

Sample:http://download.csdn.net/detail/qq_26787115/9685567