Search code examples
androidviewlineandroid-canvasz-order

Drawing line under view in android


I am using the onDispatchDraw(Canvas canvas) method to draw lines in my view. When I call canvas.drawLine() it always draws the line on top of all my views. Is there any way to draw the line under a button but on top of another view in my layout using canvas.drawLine()?

I have tried the following but it still draws the line over the button.

Button b;
RelativeLayout r;
@Override
protected void dispatchDraw(Canvas canvas) {
     super.dispatchDraw(canvas);

     Paint p = new Paint();
     p.setColor(Color.Black);

     canvas.drawLine(0,0,100,100,p);

     r.removeView(b);
     r.addView(b);
}

Solution

  • You're trying to reinvent the wheel. Z-ordering is already implemented in the window management subsystem and you can use it.

    1. Create a custom view you want to draw on.
    2. Make it non-clickable using android:clickable="false" or setClickable(false).
    3. Make its background transparent and implement dispatchDraw().
    4. Put all the views you don't want to draw on above this view in the view hierarchy.