Android rounded corners in ListView

与世无争的帅哥 提交于 2019-12-04 14:14:12

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

You can implement it using the 9-pitch images use in background. Please check the doc for it on android site.

Thank you

Richard Le Mesurier

You could make a transparent 9Patch image with rounded corners, and use it as a mask to overlay your LinearLayout. That way, it does not matter if the selector's bleed out - the mask will always overlay that problem.

I needed to find a good way of masking out any of my layouts to create the typical iOS-style layouts.

I wrote quite a complete answer on that in question: Android XML rounded clipped corners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!