简体   繁体   English

没有根元素的Android自定义视图布局声明

[英]Android custom view layout declaration without root element

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: 我已经完成了自定义视图的工作,但是如果我为以下layout.xml进行充气,它将始终与父视图匹配:

custom_view.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 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. 但是,当自定义视图加载并附加时,我看到其计算出的大小(来自onMeasure )是设备屏幕的大小。

Do I really need to declare the layout.xml as: 我真的需要将layout.xml声明为:

custom_view.xml 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. 似乎有点没有意义,因为我实际上不关心LinearLayout,也不想记住我放进膨胀的R.layout.custom_view中的内容。

Wow, this is very interesting! 哇,这很有趣! Thanks to the following article: 感谢以下文章:

http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ 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. 基本上,如果您在未指定父项的情况下对布局进行充气,则将丢弃布局xml根目录中指定的所有layout_xxx属性。 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. 另外,请注意,如果传递true(附加到root),则返回的元素将是提供的父元素。 Pay attention to this as it may cause problems when you're expecting the inflated layout to be returned! 请注意这一点,因为当您期望返回膨胀的布局时,它可能会引起问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM