2016-12-14 59 views
0

我試圖創建一個可重複使用的佈局included.xml然後可以注入其他佈局和通過標籤屬性進行自定義。下面是我有:Android數據綁定:無法注入屬性到「包含」標籤

res/layout/parent.xml

<?xml version="1.0" encoding="utf-8"?> 
<layout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/com.myself.fancyapp" 
    > 

    <include layout="@layout/included" 
      app:src123="@drawable/my_icon" /> 

</layout> 

res/layout/included.xml

<?xml version="1.0" encoding="utf-8"?> 
<layout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    > 
    <data> 
     <variable name="src123" type="android.graphics.drawable.Drawable" /> 
    </data> 

    <android.support.design.widget.FloatingActionButton 
     android:src="@{src123}" /> 
</layout> 

app/build.gradle

android { 
    compileSdkVersion 23 
    buildToolsVersion "23.0.2" 

    dataBinding { 
     enabled = true 
    } 
    .... 
} 

dependencies { 
    compile 'com.android.support:appcompat-v7:23.1.1' 
    compile 'com.android.support:design:23.1.1' 
} 

作爲一個結果,我嘗試注入的按鈕不包含任何圖像。

如果parent.xml我改變xmlns:appres-auto,我在app/build/intermediate/data-binding-layout-out/debug/layout/parent.xml以下錯誤:

Error:(17) No resource identifier found for attribute 'src123' in package 'com.myself.fancyapp'

沒有任何人有一個想法,爲什麼出現這種情況,如何解決這一問題?謝謝。

+0

'的xmlns:程序= 「http://schemas.android.com/apk/res-auto」'記住這parent.xml,看到了輸出 –

+0

@RaviRupareliya感謝您的建議,但是,如前所述在我的文章的最後部分,它會引發編譯時錯誤。 – stillwaiting

+0

要確認您是否在使用parent.xml的類中實現DataBinding?或者你只是使用'setContentView'或'inflater'作爲parent.xml文件? –

回答

2

的問題是,你不使用綁定語法變量:

<include layout="@layout/included" 
     app:src123="@drawable/my_icon" /> 

應該是:

<include layout="@layout/included" 
     app:src123="@{@drawable/my_icon}" /> 

無關,但我不認爲包括被允許作爲佈局的根元素。我相信你將不得不圍繞包含一個正常的觀點。

<?xml version="1.0" encoding="utf-8"?> 
<layout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/com.myself.fancyapp" 
    > 

    <FrameLayout android:layout_width="match_parent" 
       android:layout_height="match_parent"> 
     <include layout="@layout/included" 
       app:src123="@{@drawable/my_icon}" /> 
    </FrameLayout> 
</layout> 
+0

謝謝,喬治,這工作就像一個魅力! – stillwaiting

相關問題