Samarth Kejriwal
Samarth Kejriwal

Reputation: 1176

How to show X labels on marker view in Line Chart?

How to show the x-axis values in the line chart on the marker view.I have used the getVal() function to get the y-axis values but how to get the x-axis values on the marker view..Below is my code for the marker view.

    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);
  }

}

Upvotes: 1

Views: 2293

Answers (1)

Madhu
Madhu

Reputation: 583

There is no direct method to get x value in MPAndroidChart 2.2.x By sending the xvalues array to the MarkerView you can get it easily. See the below MarkerView implementation.

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();
    }
}

set the `MarkerView' to chart

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);

Or if you use MPAndroidChart 3.0.0, get the x value like this

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

Upvotes: 2

Related Questions