一直以来,图标类UI都用MPAndroidChart这个库,但是今天今天感觉不好了,想实现一个标签,并可点击,我以为这玩意肯定支持,结果在库里找了好久,发现没有,然后我的第一想法就是,这玩意要重写touch,然后处理一些逻辑。 but,我还是到源码里找了一圈还是木有,想这个需求应该不是很古怪,就到issues里see see,果然有!!!Make MarkerView Click
不出我所料。
- 继承LineChart(其他chart也可),转移touch事件
public class MyChart extends LineChart {
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = true;
// if there is no marker view or drawing marker is disabled
if (isShowingMarker() && this.getMarker() instanceof ChartInfoMarkerView){
//
ChartMarkerView markerView = (ChartMarkerView) this.getMarker();
Rect rect = new Rect((int)markerView.drawingPosX,(int)markerView.drawingPosY,(int)markerView.drawingPosX + markerView.getWidth(), (int)markerView.drawingPosY + markerView.getHeight());
if (rect.contains((int) event.getX(),(int) event.getY())) {
// touch on marker -> dispatch touch event in to marker
markerView.dispatchTouchEvent(event);
}else{
handled = super.onTouchEvent(event);
}
}else{
handled = super.onTouchEvent(event);
}
return handled;
}
private boolean isShowingMarker(){
return mMarker != null && isDrawMarkersEnabled() && valuesToHighlight();
}
}
- 自定义MarkerView,接管点击事件
public class ChartMarkerView extends MarkerView {
@BindView(R.id.markerview_root)
LinearLayout markerContainerView;
protected float drawingPosX;
protected float drawingPosY;
private static final int MAX_CLICK_DURATION = 500;
private long startClickTime;
private MarkerViewClickCB cb;
public void setMarkerViewClickCB(MarkerViewClickCB cb) {
this.cb = cb;
}
public ChartInfoMarkerView(Context context, int layoutResource) {
super(context, layoutResource);
ButterKnife.bind(this);
markerContainerView.setClickable(true);
markerContainerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (cb != null) cb.onMarkerViewClick();
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
startClickTime = Calendar.getInstance().getTimeInMillis();
break;
}
case MotionEvent.ACTION_UP: {
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if(clickDuration < MAX_CLICK_DURATION) {
markerContainerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (cb != null) cb.onMarkerViewClick();
}
});
}
}
}
return super.onTouchEvent(event);
}
@Override
public void draw(Canvas canvas, float posX, float posY) {
super.draw(canvas, posX, posY);
MPPointF offset = getOffsetForDrawingAtPoint(posX, posY);
this.drawingPosX = posX + offset.x;
this.drawingPosY = posY + offset.y;
}
}
- 自定义接口,回调点击事件到合适的地方
public interface MarkerViewClickCB {
void onMarkerViewClick();
}