如何在折线图中的标记视图上显示X标签?

时间:2016-07-16 15:53:08

标签: java android mpandroidchart

如何在标记视图的折线图中显示x轴值。我使用了getVal()函数来获取y轴值,但是如何在标记视图上获取x轴值。下面是我的标记视图代码。

    public class MymarkerView extends MarkerView
{
private TextView indices;

public MymarkerView(Context context, int layoutResource) {
    super(context, layoutResource);
    indices = (TextView) findViewById(R.id.indices);
}

// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
@Override
public void refreshContent(Entry e, Highlight highlight) {

        indices.setText("Indices:" +e.getVal());
  }

@Override
public int getXOffset(float xpos) {
    // this will center the marker-view horizontally
    return -(getWidth() / 2);

}

@Override
public int getYOffset(float ypos) {
    // this will cause the marker-view to be above the selected value
    return -getHeight();
}
public void draw(Canvas canvas, float posx, float posy)
{
    // take offsets into consideration
    posx += getXOffset(posx);
    posy=0;
    // AVOID OFFSCREEN
    if(posx<65)
        posx=65;
    if(posx>350)
        posx=350;

    // translate to the correct position and draw
    canvas.translate(posx, posy);
    draw(canvas);
    canvas.translate(-posx, -posy);
  }

}

1 个答案:

答案 0 :(得分:0)

在MPAndroidChart 2.2.x中没有直接获取x值的方法 通过将xvalues数组发送到MarkerView,您可以轻松获得它。 请参阅下面的MarkerView实施。

public class MymarkerView extends MarkerView
{
    ArrayList<String> mXLabels;

    public MymarkerView(Context context, int layoutResource, ArrayList<String> xLabels) {
        super(context, layoutResource);
        mXLabels = xLabels;
    }

    @Override
    public void refreshContent(Entry e, Highlight highlight) {
        //get x value
        String xVal= mXLabels.get(e.getXIndex());
    }

    @Override
    public int getXOffset(float xpos) {
        // this will center the marker-view horizontally
        return -(getWidth() / 2);

    }

    @Override
    public int getYOffset(float ypos) {
        // this will cause the marker-view to be above the selected value
        return -getHeight();
    }
}

设置`MarkerView&#39;图表

ArrayList<String> xVals = new ArrayList<>();
//add labels to xVals
....
....

LineData lineData = new LineData(xVals, dataSets);

lineChart.setMarkerView(new MymarkerView(context, R.layout.custom_marker_view_layout, xVals);
lineChart.setData(lineData);

或者,如果您使用 MPAndroidChart 3.0.0 ,请像这样获取x值

@Override
    public void refreshContent(Entry e, Highlight highlight) {
        //get x value
       float xVal = e.getX();
    }