调用invalidate后,Android Custom View显示纯黑色

Pin*_*azz 9 android android-custom-view android-canvas android-relativelayout

在这段代码中,我想在两个ImageView的顶部之间画一条线.但是,在运行应用程序时,自定义视图在调用后显示为纯黑色invalidate().

这是我的代码:

public class ArrowView extends RelativeLayout {
    public Paint paint;
    public Bitmap eraser;
    public Canvas cacheCanvas;

    public float leftX;
    public float leftY;

    public float rightX;
    public float rightY;

    public boolean update = false;

    public ImageView iv_leftArrow;
    public ImageView iv_rightArrow;

    private int w;
    private int h;

    LayoutInflater mInflater;

    public ArrowView(Context context) {
        super(context);
        this.setWillNotDraw(false);
        mInflater = LayoutInflater.from(context);
        init();
    }

    public ArrowView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setWillNotDraw(false);
        mInflater = LayoutInflater.from(context);
        init();
    }

    public ArrowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setWillNotDraw(false);
        mInflater = LayoutInflater.from(context);
        init();
    }

    @Override
    public void onSizeChanged(int w, int h, int oldW, int oldH) {
        this.w = w;
        this.h = h;
        super.onSizeChanged(w, h, oldW, oldH);
    }

    public void init() {
        View v = mInflater.inflate(R.layout.arrow_view, this, true);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(5);
        v.setBackgroundColor(Color.TRANSPARENT);

        eraser = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        iv_leftArrow = (ImageView) v.findViewById(R.id.iv_leftarrow);
        iv_rightArrow = (ImageView) v.findViewById(R.id.iv_rightArrow);

        cacheCanvas = new Canvas();
        cacheCanvas.setBitmap(eraser);
    }

    public void setCoordinates(float leftX, float leftY, float rightX, float rightY) {
        this.leftX = leftX;
        this.leftY = leftY;
        this.rightX = rightX;
        this.rightY = rightY;
    }

    @Override
    public void onDraw(Canvas c) {
        super.onDraw(c);
        setCoordinates(iv_leftArrow.getX() + iv_leftArrow.getWidth() / 2, iv_leftArrow.getY(), iv_rightArrow.getX() + iv_rightArrow.getWidth() / 2, iv_rightArrow.getY() );
        if (update) {
            c.drawLine(leftX, leftY, rightX, rightY, paint);
            update = false;
        }
        cacheCanvas.drawPath(p, paint);
    }
}
Run Code Online (Sandbox Code Playgroud)

调用后自定义视图显示为纯黑色是否有任何理由invalidate()

SQL*_*oob 0

如您所知,invalidate()用于通过调用来更新视图onDraw

我认为你所做的就是在将 update 设置为 true 之前调用它 - 所以你的 onDraw方法根据它的声音运行了一个错误的更新。