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

Upvotes: 0

Views: 4451

Answers (3)

Ron
Ron

Reputation: 24235

Call super.dispatchDraw() after drawing the line. The dispatchDraw is called by viewgroup for drawing its children, so in your case, calling super.dispatchDraw() will draw the button first then you are drawing the line over it. Do dispatchDraw this way :

Updated code

class myListViewWithLine extends ListView {
....
    @Override
    protected void dispatchDraw(Canvas canvas) {

         Paint p = new Paint();
         p.setColor(Color.Black);
         canvas.drawLine(0,0,100,100,p);

         super.dispatchDraw(canvas);
    }
....
}

Upvotes: 2

Michael
Michael

Reputation: 54705

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.

Upvotes: 4

blessanm86
blessanm86

Reputation: 31779

Another method will be to just add a view with 1 dip as height and background color whatever you like under the button. It should look like like a line.

View v = new View(this);
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,1);
v.setLayoutParams(lp);
v.setBackgroundColor(Color.WHITE);

addView(v,INDEX NUMBER AFTER THE BUTTON);

Upvotes: 0

Related Questions