Search code examples
androidbackgrounddrag-and-dropandroid-edittextclipping

Android:clipChildren Causes Custom View's Background To Draw Full Height Of Screen


I have custom EditTexts and I noticed their backgrounds draw wrong when they leave their parents. So I used android:clipChildren="false" on their parent. That works fine. They draw correctly when partially out of their parent now.

This gave me a new problem though. On older devices (< Android 2.3? Not confirmed what the max version is for this issue), the background doesn't get clipped to it's padding. The EditText backgrounds are now drawing to the full height/width of the screen. This only happens on the initial layout.

Has anyone experienced this before? It's really weird. I don't get why the background only draws wrong when using android:clipChildren="false" and only on some devices. I need that though since my EditTexts can be dragged around and need to keep drawing outside their parent container.


Solution

  • I just ran across the same problem. It was caused by having ColorDrawables as background (a StateListDrawable (<selector>) containing several @color/... items, to be exact).

    It looks like this was fixed in Android 3.2.4-r1 (commit 95930e1).

    Before that, the class comment used to say:

    Note that a ColorDrawable [...] ignores the Bounds, meaning it will draw everywhere in the current clip even if setBounds(...) was called with a smaller area.

    This was removed, and the draw(Canvas) method changed to respect the bounds.


    As a workaround, if you need to support older Android versions, you can use a ShapeDrawable with a solid color to get the same behaviour:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
           android:shape="rectangle">
        <solid android:color="@color/your_background_color"/>    
    </shape>