I\'m building a complex layout and I want to use include
tag for my custom component, like this:
It's not possible to attributes other than layout params, visibility or ID on an include tag. This includes custom attributes.
You can verify this by looking at the source of the LayoutInflater.parseInclude method, around line 705: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/view/LayoutInflater.java#640
The inflater only applies the ID and visibility attributes to the included layout.
Unfortunately, the only thing I can contribute is that I was also unable to set custom attributes on an include tag, and have them pass through to the included layout.
It may well not be possible at this point.
You have to include in your root xml element your custom namespace. If your package name is com.example.test your xml shold be something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:txt="http://schemas.android.com/apk/res/com.example.test" />
A nice tutorial is: http://blog.infidian.com/2008/05/02/android-tutorial-42-passing-custom-variables-via-xml-resource-files/
It's not possible to use with custom attributes, or any attributes other than the ones stated on the API page (up through at least 5.0.0):
https://code.google.com/p/android/issues/detail?id=38023
http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/5.0.0_r2-robolectric-1/android/view/LayoutInflater.java
I had the same question. After visiting this thread, I ended up using View
's setTag()
methods to attach identifying information to each View
during onCreate()
, and then getTag()
methods to retrieve it later on.
I know this is an old question but I came across it and found that it is now possible thanks to Data Binding.
First you need to enable Data Binding in your project.
Then add data binding to the layout you want to include:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="title" type="java.lang.String"/>
</data>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/screen_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="center">
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textStyle="bold"
android:text="@{title}"/>
...
</RelativeLayout>
</layout>
Finally, pass the variable from the main layout to the included layout like this:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
...
</data>
...
xmlns:app="http://schemas.android.com/apk/res-auto"
...
<include layout="@layout/included_layout"
android:id="@+id/title"
app:title="@{@string/title}"/>
...
</layout>