开发者

How to disable layout optimisation in pre-2.2 Android?

开发者 https://www.devze.com 2023-02-06 14:30 出处:网络
I\'ve created a custom component based on a LinearLayout. The idea is to make it a part of the XML layout, like:

I've created a custom component based on a LinearLayout. The idea is to make it a part of the XML layout, like:

<com.test.MyComponent 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_hori开发者_如何学JAVAzontal"
    />

At runtime, the component creates its content dynamically (by adding instances of a View subclass). This works perfectly well on Android 2.2 and 2.3 but on the earlier platforms the component is simply not displayed. I spent a lot of time to figure out why it disappears and finally was able to figure out the reason.

On pre-2.2 platforms, Android does a "clever" optimisation. It figures out that the custom class used in the XML layout is a LinearLayout, and it doesn't have any children - so it doesn't bother displaying it at all.

I have tried numerous workarounds. The only one that was more or less successful is adding to the component a dummy view, so that it wasn't empty:

<com.test.MyComponent 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal"
    >
    <View
        android:layout_width="1px"
        android:layout_height="1px"
        />
</com.test.MyComponent>

And then adding to the component's code the following override:

protected void dispatchDraw (Canvas canvas) {
    super.dispatchDraw(canvas);

    for (ChildView c : children) {
        c.draw(canvas);
    }
}

This allowed the component and its contents to appear, but the presence of the dummy view messed up the interaction with the component, and any attempt to hide the dummy causes the component to disappear.

Looks like someone has put quite a lot of effort into creating an optimisation that now causes me to spend the whole day to get rid of it. Does anybody know, if there is a way to disable this "helpful" optimisation?


There's no such optimization. A view is not drawn if it has a size of 0, doesn't intersect with the clipping rectangle or if it's entirely covered by an opaque view. BTW, a layout will not invoke its onDraw() method if you don't call setWillNotDraw(false) before.

Your problem sounds more like a layout issue. Did you implement onMeasure()? Showing us the relevant parts of your implementation would help.

0

精彩评论

暂无评论...
验证码 换一张
取 消