onDraw() is not called in custom View

≯℡__Kan透↙ 提交于 2021-01-29 09:47:43

问题


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. I have a custom view called DrawView, in which I want to draw my results. I call the drawPoint method from my service whenever a step is measured. Then from my drawPoint method I try to call onDraw() using invalidate(). According to my logs, drawPoint is being called but onDraw() is not. So my question is:

Why is onDraw() not being called, and how should I make DrawView call it?


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

回答1:


Instead calling directly view.drawPoint() from service, use handler to update the ui.

Check the link update ui from background service




回答2:


invalidate() must be called from the UI thread. Try calling postInvalidate() instead.

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



来源:https://stackoverflow.com/questions/17470620/ondraw-is-not-called-in-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!