Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom listview drawing

Tags:

android

I am trying to draw an overlay above my ListView. So i went with the most obvious approach and put my custom drawing code beneath super.onDraw(canvas) in my ListView subclass.

To my surprise the list was rendered above my custom drawing. I know this can easily be done by wrapping the ListView in a FrameLayout but i don't think it is neccesary to inflate another view. A fix and an explanation of why i ran into this problem would be awesome, thanks!

My draw code looks something like this:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawRect(rect, paint);
}
like image 453
Emil Sjölander Avatar asked Mar 19 '26 17:03

Emil Sjölander


2 Answers

The thing about the ListView is that it isn't actually drawing the list contents. That's handled by the Adapter bound to the list -- or more specifically the Views created by that Adapter that populate the ListView.

The onDraw of the ListView happens before the contained Views are created and displayed.

Drawing things on top of a ListView can be expensive, as you're compositing another layer above an already complex View. Placing another View on top (using a FrameLayout as you suggest) is probably the "best" way to do what you're attempting, or alternatively (depending on the effect you're trying to achieve), you could modify the Adapter or Views to display the data you're trying to overlay.

like image 50
Reto Meier Avatar answered Mar 21 '26 07:03

Reto Meier


Overriding dispatchDraw instead of onDraw seems to do what you want:

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    ...
}
like image 29
BoD Avatar answered Mar 21 '26 08:03

BoD