简体   繁体   English

自定义视图中未调用onDraw()

[英]onDraw() is not called in custom View

For an app I am developing, I want to graph the results from a pedometer. 对于我正在开发的应用程序,我想绘制计步器的结果。 The pedometer uses a service to measure the amount of steps someone makes in the background. 计步器使用一项service来测量某人在后台执行的步数。 I have a custom view called DrawView, in which I want to draw my results. 我有一个名为DrawView的自定义视图,我想在其中绘制结果。 I call the drawPoint method from my service whenever a step is measured. 每当测量步骤时,我都会从service调用drawPoint方法。 Then from my drawPoint method I try to call onDraw() using invalidate() . 然后从我的drawPoint方法尝试使用invalidate()调用onDraw() invalidate() According to my logs, drawPoint is being called but onDraw() is not. 根据我的日志,drawPoint被调用,而onDraw()没有被调用。 So my question is: 所以我的问题是:

Why is onDraw() not being called, and how should I make DrawView call it? 为什么不调用onDraw(),如何使DrawView调用它?


public class DrawView extends View {

...

@Override
public void onDraw(Canvas canvas) {
    for (Point point : points) {
        canvas.drawCircle(point.x, point.y, 5, paint);
        Log.d("Checks", "onDraw is called");
    }
}

public void drawPoint(int counter) {
    Log.d("Checks", "Point coordinates: " + 40 + ", " + counter);

    Point point = new Point();
    point.y = 40;
    point.x = counter;
    points.add(point);
    invalidate();
}
}

Instead calling directly view.drawPoint() from service, use handler to update the ui. 代替直接从服务调用view.drawPoint(),使用处理程序来更新ui。

Check the link update ui from background service 从后台服务检查链接更新ui

invalidate() must be called from the UI thread. 必须从UI线程调用invalidate()。 Try calling postInvalidate() instead. 尝试改为调用postInvalidate()。

http://developer.android.com/reference/android/view/View.html#invalidate() http://developer.android.com/reference/android/view/View.html#invalidate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM