是否可以在没有包装根元素的情况下使用自定义 View 布局声明布局?我的自定义 View 可以正常工作,但如果我膨胀以下 layout.xml,它总是与父 View 匹配:
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>
但是当自定义 View 加载并附加时,我看到它的计算大小(来自 onMeasure
)是设备屏幕的大小。
我真的需要将 layout.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>
这似乎有点毫无意义,因为我实际上并不关心 LinearLayout,也不想记住我在膨胀的 R.layout.custom_view 中转换了什么。
最佳答案
哇,这很有趣!感谢以下文章:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
基本上,如果您在没有指定父级的情况下扩充布局,则布局 xml 根目录中指定的所有 layout_xxx
属性都将被丢弃。你应该将你的布局膨胀为
inflater.inflate(R.layout.your_layout, parent, false);
另请注意,如果您传递 true(附加到根),则返回的元素将是提供的父元素。请注意这一点,因为当您期望返回膨胀的布局时,它可能会导致问题!
关于没有根元素的Android自定义 View 布局声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529705/