Reputation: 735
Is there any way to have fixed position for MarkerView? I need to have it fixed in top left or top right corner.
Upvotes: 4
Views: 2919
Reputation: 211
MpandroidChart v3.1.0 :
class MarkerView constructor(
context: Context,
) :
MarkerView(context, R.layout.marker_view) {
private val totalWidth = resources.displayMetrics.widthPixels
override fun refreshContent(e: Entry?, highlight: Highlight?) {
//...
super.refreshContent(e, highlight)
}
override fun getOffsetForDrawingAtPoint(posX: Float, posY: Float): MPPointF {
val supposedX = posX + width
val mpPointF = MPPointF()
mpPointF.x = when {
supposedX > totalWidth -> -width.toFloat()
posX - width < 0 -> 0f
else -> 0f
}
mpPointF.y = if (posY > height)
-height.toFloat()
else
0f
return mpPointF
}
}
in this implementation the default location for MarkerView is to the top-right of the point, if there is enough space, else may be to top-left , bottom-left or bottom-right of it .you can change this behaviour based on your needs.
notice that this only Workes if chart's width is set to MATCH_PARENT.
Upvotes: 1
Reputation: 151
getXOffset(float xpos) and getYOffset(float ypos) are not overridden by the MarkerView class anymore. To fix the Marker position, You have to override the getOffsetForDrawingAtPoint(float posX, float posY) method in the following way:
private MPPointF mOffset;
@Override
public MPPointF getOffsetForDrawingAtPoint(float posX, float posY) {
if(mOffset == null) {
// center the marker horizontally and fixed Y position at the top
mOffset = new MPPointF(-(getWidth() / 2f), -posY);
}
return mOffset;
}
Upvotes: 2
Reputation: 31
This is one approach to fix the marker on the Top Left or Top Right
Once you've created the custom MarkerView here's what you can do.
1) You can set an id to the parent view/layout and using that id you can get it's width.
layoutWidth = customLayout.getWidth();
2) You can then override draw and do the following:
@Override
public void draw(Canvas canvas, float posX, float posY) {
if (posX > (canvas.getWidth() / 2.0))
//Check if the user is in the right half of the canvas
super.draw(canvas, leftXPos, leftYPos);
//Draw marker on the left top corner
else
//Otherwise draw the marker on the top right corner.
super.draw(canvas, canvas.getWidth() - layoutWidth, rightYPos);
}
You can set the values for leftXPos, leftYPos and rightYPos to whatever looks and feels best.
Hope this helps!
Upvotes: 3
Reputation: 416
You should create a custom MarkerView, like in the documentation.
Then, customize getXOffset and getYOffset like this:
@Override
public int getXOffset(float xpos) {
// this will cause the marker-view to be at left of the screen
return -(int)xpos;
}
@Override
public int getYOffset(float ypos) {
// this will cause the marker-view to be at top screen
return -(int)ypos;
Upvotes: 2