Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android rounded corners in ListView

I have a ListView with rounded corners made using following shape as background:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:bottomRightRadius="13px" android:bottomLeftRadius="13px" android:topLeftRadius="13px" android:topRightRadius="13px"/>
</shape>

The problem lies in the selector. It's rectangle shaped, so when selecting first or last item the corners aren't rounded anymore. I've found a very nice solution in the last post at http://www.anddev.org/view-layout-resource-problems-f27/rounded-corners-on-listview-t8193-15.html. The problem is I can't make another class to inherit from ListView. How can I apply this method when the only thing I have is the reference to existing ListView? The reason I have to do it this way is that the layout is inflated from xml.

I'm looking for something like:

ListView lv = (ListView)findViewById(...);
lv.onSizeChanged = protected void onSizeChanged(int w, int h, int oldw, int oldh){ ... }

Thanks

like image 484
Sebastian Nowak Avatar asked Jan 18 '26 20:01

Sebastian Nowak


1 Answers

Looks like there's no other way than extending the ListView class and using it in XML. Here's the sample code:

public class WListView extends LinearLayout
{
    // =================================================================
    // Variables
    // =================================================================
    private Path clipArea;

    // =================================================================
    // Public methods
    // =================================================================

    public WListView(Context context)
    {
        super(context);
    }

    public WListView(Context context, AttributeSet attr)
    {
        super(context, attr);
    }

    // =================================================================
    // Private methods
    // =================================================================


    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH)
    {
        super.onSizeChanged(w, h, oldW, oldH);
        clipArea = new Path();
        RectF rect = new RectF(0, 0, w, h);

        int cornerRadius = 13; // we should convert px to dp here
        clipArea.addRoundRect(rect, cornerRadius, cornerRadius, Path.Direction.CW);
    }

    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        canvas.save();
        canvas.clipPath(clipArea);
        super.dispatchDraw(canvas);
        canvas.restore();
    }
}
like image 62
Sebastian Nowak Avatar answered Jan 21 '26 10:01

Sebastian Nowak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!