Android setBackgroundColor没有给出任何结果

时间:2015-04-26 13:10:03

标签: android

在我的申请中,我希望得到类似的东西。

enter image description here

这是代码

public class Tunnel extends View {
    Paint paint = new Paint();
    Toast toast;

    public Tunnel(Context context) {
        super(context);

        setBackgroundColor(Color.BLACK);
        paint.setColor(Color.WHITE);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (toast != null) {
                    toast.cancel();
                }
                int x = (int) event.getX();
                int y = (int) event.getY();

                if (y > myFunction(x) + 100 || y < myFunction(x)) {
                    toast = Toast.makeText(getContext(), "Out of bounds", Toast.LENGTH_SHORT);
                } else {
                    toast = Toast.makeText(getContext(), "Perfect", Toast.LENGTH_SHORT);
                }
                toast.show();
                return false;
            }
        });
    }

    @Override
    public void onDraw(Canvas canvas) {
        for (int x = 0; x < canvas.getWidth(); x++) {
            //upper bound
            canvas.drawPoint(x, (float) myFunction(x), paint);

            //lower bound
            canvas.drawPoint(x, (float) myFunction(x) + 100, paint);

            canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
        }
    }

    private double myFunction(double x) {
        return 50 * Math.sin(x / 50) + 400;
    }
}

但不是那样,我得到了一个白色的屏幕。 onDraw方法工作正常,我用红色测试了它,但为什么setBackgroundColor没有工作?我做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,我发现了问题。我需要移动线

setBackgroundColor(Color.BLACK);

进入onDraw方法,所以我看起来像这样

 @Override
    public void onDraw(Canvas canvas) {
        for (int x = 0; x < canvas.getWidth(); x++) {
            //upper bound
            canvas.drawPoint(x, (float) myFunction(x), paint);

            //lower bound
            canvas.drawPoint(x, (float) myFunction(x) + 100, paint);

            canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
        }
        setBackgroundColor(Color.BLACK);
    }