Pergunta

Is it possible to declare a layout with a custom view layout without a wrapping root element? I've got my custom view working but it always matches the parent if I inflate the following layout.xml:

custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<com.company.ui.CustomView
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="@dimen/custom_view_height"
    android:layout_width="@dimen/custom_view_width" />

dimons.xml

<resources>
    <dimen name="custom_view_height">300dp</dimen>
    <dimen name="custom_view_width">400dp</dimen>
</resources>

But when the custom view loads and attaches, I see that its calculated size (from onMeasure) is the size of the device's screen.

Do I really need to declare the layout.xml as:

custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <com.company.ui.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_height="@dimen/custom_view_height"
        android:layout_width="@dimen/custom_view_width" />
</LinearLayout>

It seems a little pointless as I actually don't care for the LinearLayout nor do I want to remember what I cast into the inflated R.layout.custom_view.

Foi útil?

Solução

Wow, this is very interesting! Thanks to the following article:

http://www.doubleencore.com/2013/05/layout-inflation-as-intended/

Basically, if you inflate a layout without parent specified, all layout_xxx attributes specified within the root of the layout xml are discarded. You should inflate your layouts as

inflater.inflate(R.layout.your_layout, parent, false);

Also, note that if you pass true (attach to root), the returned element will be the parent element provided. Pay attention to this as it may cause problems when you're expecting the inflated layout to be returned!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top