簡體   English   中英

沒有根元素的Android自定義視圖布局聲明

[英]Android custom view layout declaration without root element

是否可以使用自定義視圖布局聲明布局而無需包裝根元素? 我已經完成了自定義視圖的工作,但是如果我為以下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>

但是,當自定義視圖加載並附加時,我看到其計算出的大小(來自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(附加到root),則返回的元素將是提供的父元素。 請注意這一點,因為當您期望返回膨脹的布局時,它可能會引起問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM