Android: re-using layouts using include with parameters - android

I'm creating an ordered list with a custom styling which is used in multiple places. I try to avoid extra code and to create a re-usable layout file for the list item, which can be included to ordered list with certain parameters. How I could do that?
What I have now is following:
layout_ordered_list_item.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="order"
type="java.lang.String" />
<variable
name="text"
type="java.lang.String" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/order"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_marginBottom="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#{order}"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:text="#{text}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</layout>
Then I would like to use that layout like following:
layout_ordered_list.xml
<LinearLayout>
<include layout="#layout/layout_ordered_list_item"
bind:order="1"
bind:text="First text content"/>
<include layout="#layout/layout_ordered_list_item"
bind:order="2"
bind:text="Second text content"/>
etc.
</LinearLayout>
Note that I'm not interested about setting variables in code dynamically. I use these layouts only with hard-coded values (or with string resources) like in my example. But since I'm using these so many times, I don't want to copy-paste list item again and again just to alter order and text content. I also know that my example is not working, it's here just to demonstrate how I would like it to work.
I've already searched the answer from Android documents but there is no example like that.
https://developer.android.com/training/improving-layouts/reusing-layouts.html
https://developer.android.com/topic/libraries/data-binding/index.html#includes
Pretty much identical question has been also asked before in SO but there is no usable answer either: How to Re-using Layouts with <include/> with parameters?

You should be able to achieve what you want by using the databinding library to inflate the including layout, and then passing in the hard coded text using a databinding statement.
Details on the databinding expression language can be found here.
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<LinearLayout>
<include layout="#layout/layout_ordered_list_item"
bind:order="#{`1`}"
bind:text="#{`First text content`}"/>
<include layout="#layout/layout_ordered_list_item"
bind:order="#{`2`}"
bind:text="#{`Second text content`}"/>
</LinearLayout>
</layout>

Related

Pass data to <include> layout using Databinding

I've been searching this a lot today and only found some unclear answers regarding this question.
I'm having multiple TextView and EditText in a form, all of them being customised by my theme and i'd like to reuse the same included layout each time, but having parameters to it like the text inside the TextView or hint inside the EditText.
My form.xml right now:
<LinearLayout android: orientation="horizontal">
<TextView android:text="Username"/>
<EditText android:id="edittext_username"
android:hint="Enter username..."
android:inputType="text"/>
</LinearLayout>
<LinearLayout android: orientation="horizontal">
<TextView android:text="Password"/>
<EditText android:id="edittext_password"
android:hint="Enter password..."
android:inputType="password"/>
</LinearLayout>
... other fields ...
What i'd like in the main form.xml:
<LinearLayout android:orientation="vertical" ...>
<include layout="form_edittext"
app:textview_text="#{`Username`}"
app:edittext_hint="#{`Enter username...`}"
... other parameters ...
/>
<include layout="form_edittext"
app:textview_text="#{`Password`}"
app:edittext_hint="#{`Enter password...`}"
... other parameters ...
/>
</LinearLayout>
also the form_edittext.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="textview_text" type="java.lang.String"/>
<variable name="edittext_id" type="java.lang.String"/>
<variable name="edittext_inputType" type="java.lang.String"/>
<variable name="edittext_hint" type="java.lang.String"/>
</data>
<TextView android:text="#{textview_text}"/>
<EditText android:id="#{edittext_id}"
android:hint="#{edittext_hint}"
android:inputType="#{edittext_inputType}"/>
</layout>
I'm still a beginner and i do not know if this is possible.
On this post, the guy replied he used data binding (as in example shown by me)
How to Re-using Layouts with <include/> with parameters? (you may see the first answer).
However, using this method give me the error of XML not recognizing identifiers like "textview_text" (the variables that i'm accessing via #{...}. If you got other solutions i'd appreciate if you share them. Cheers!
UPDATE on iCantC's answer: (but the textview's text and the hint remain empty).
Main layout:
<?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"
xmlns:tools="http://schemas.android.com/tools">
...
<include layout="#layout/activity_login_layout_input"
android:id="#+id/activity_login_layout_input_emailAddress"
app:textviewt="#{#string/email}" //the string is "Email Address"
app:edittexth="#{#string/emailhint}" /> //the string is "Your email address..."
...
</layout>
Included layout:
<layout>
<data>
<variable
name="textviewt"
type="String"/>
<variable
name="edittexth"
type="String"/>
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:showDividers="middle">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{textviewt}"
android:textColor="#color/c1"
android:textSize="12sp"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingEnd="26dp">
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/edittext"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center|start"
android:layout_marginStart="26dp"
android:background="#drawable/activity_login_background"
android:hint="#{edittexth}"
android:padding="6dp"
android:textAlignment="center"
android:textColor="#color/c2"
android:textColorHint="#color/grey"
android:textSize="14sp"/>
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="start"
android:adjustViewBounds="true"
android:src="#drawable/activity_login_edittext_drawable" />
</FrameLayout>
</LinearLayout>
</layout>
It seems like you want to include a common layout and then pass dynamic parameters from the main layout to included layout, here are the steps,
Step 1: Enable DataBinding in your project
//In the build.gradle file in the app module, add this
android {
...
dataBinding {
enabled = true
}
}
Step 2: Create your common_layout_included.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="username"
type="String"/>
</data>
<LinearLayout
..
>
<TextView
android:id="#+id/tv_username"
android:text="#{username}"/>
</LinearLayout>
</layout>
Step 3: Include common_layout_included.xml in your main_layout.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">
<LinearLayout
..
>
<include
android:id="#+id/includedLayout"
layout="#layout/common_layout_included"
app:username="#{#string/username}" // here we pass any String
/>
</LinearLayout>
</layout>
Step 4: Make sure you inflate the layout using DataBinding way
//In the onCreate of your Activity
val binding = DataBindingUtil.setContentView(this,R.layout.main_layout)
That's it, you are good to go. If still some error appears just do File -> Invalidate Caches/Restart
One last thing, I saw that you are assigning the id's to the view's dynamically android:id="#{edittext_id}", in all of my experience, I never really encountered a use case where I would be motivated to do this. I don't even know if it's possible and even if possible I doubt it's a good practice.

How to set a layout default value from parent layout using databinding and <include> tag in order to see it in preview?

I'm trying to use a view with databinding using the include tag multiple times.
It works great when the app runs, but in preview I don't manage to make it work in the parent.
Instead, I can do it on the view itself, but it implies that if I use it 5 times in the same layout, I'll have 5 exact copies. It's not a blocking issue, but for debugging/ UI, it makes things a bit more complicated.
Here's the code of the replicated view:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View"/>
<import type="android.text.TextUtils"/>
<variable
name="title"
type="String" />
<variable
name="value"
type="String" />
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:text="#{(!TextUtils.isEmpty(title) ? title : `Title`).concat(`:`), default=`Title:`}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#{!TextUtils.isEmpty(value) ? #color/darkBlue : #color/red, default=#color/red }"
android:text="#{(!TextUtils.isEmpty(value) ? value : `Unknown`), default=`Unknown`}" />
</LinearLayout>
</layout>
And here's how it's included:
<include layout="#layout/titled_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
bind:title="#{`Firstname`}"
bind:value="#{user.firstName}" />
In Android it looks like this
But in preview it looks like this
Does anyone know how to fix it ?
Thanks, and have a good day in those complicated times.
Store your string in string.xml
And set that as default value
Like below
android:text='#{viewModel.firstName, default=#string/firstName}`

How to hide included merge layout - Kotlin null exception

I need to hide the visibility of my layout but because it's an included layout with the merge tag I'm not being able to do it. I'm using kotlin and keep getting a null pointer exception when trying to hide the view by using
layout_bookings_past.visibility = View.GONE
with this import
import kotlinx.android.synthetic.main.layout_bookings_past.*
but tried also with
import kotlinx.android.synthetic.main.fragment_bookings.*
That's my code:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/layout_bookings_past"
layout="#layout/layout_bookings_past" />
</android.support.constraint.ConstraintLayout>
And for the merge layout I have something like:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
Thanks very much.
Ps: I've a sample app that simulates the structure of my project here
When you use <merge> tag, merged views are actually merged right into parent ConstraintLayout, so ViewGroup with id layout_bookings_past doesn't exist.
To make sure you can check your layout in Layout Inspector:
You can notice, that tv_past and rv_past are childs of ConstraintLayout that is root layout of FragmentBookings.
The solution would be to add actual ViewGroup instead of <merge> like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_past"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Past bookings"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ll_buttons" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_past"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_past"
tools:itemCount="2"/>
</android.support.constraint.ConstraintLayout>
There's another option, if we assume, that we always include this layout to ConstraintLayout. You can add android.support.constraint.Group (more info) as a child of <merge> and reference it in your code. Like this:
<android.support.constraint.Group
android:id="#+id/merged_layout"
android:layout_width="0dp"
android:layout_height="0dp"
app:constraint_referenced_ids="tv_past,rv_past"/>
And just reference it as usually:
merged_layout.visibility = View.GONE
But I guess it is just easier to add ConstraintLayout as parent of the layout. Getting rid of redundant layouts is good, but not worth it in that case.

How to bind layout with several qualifiers

I have 2 layouts: one for v19+ and another for earlier versions. They contain different views with different ids. How can I say Android DataBinding framework that I want to work with both layouts? It generates views only for one layout (selects randomly).
layout/temp_view.xml :
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="block"
type="ru.temp.model.content.blocks.WebMediaBlock" />
<import type="ru.temp.model.Types.ProviderTypes" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:background="#android:color/white">
<ImageView
android:id="#+id/provider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="#dimen/size5"
android:src="#{ProviderTypes.fromString(block.provider).getResId()}" />
</FrameLayout>
</layout>
layout-v19/temp_view.xml :
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="block"
type="ru.temp.model.content.blocks.WebMediaBlock" />
<import type="ru.temp.model.Types.ProviderTypes" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:background="#android:color/white">
<ru.temp.utils.EmbedView
android:id="#+id/media_embed"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ru.temp.structure.static_material.CreditsView
android:id="#+id/credits_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</layout>
Update:
Finally I've found out the root of the problem. I don't know why but it does not generate *BindingImpl files when use minSdkVersion 21. If specify earlier versions it works as said #yigit
Data binding will generate a base class that serves as a common interface for both (the variables). Data binding will take care of creating the right instance when you call DataBindingUtil.setContentView(activity, R.layout.tmp_view).
For instance, in your example, it will generate
TempViewBinding, TempViewBindingImpl and TempViewBindingV19Impl.
You can check these classes inside <app module>/build/intermediates/classes/<your package>/databinding/ after you compile.
TempViewBinding is the base class and it will have the combination of variables and views for each layout.
If you are not seeing them in the IDE, might be an auto-completion bug in AS (please file a bug).

import xml into another xml

I have lots of control repeated in my xml (a Button for instance). Is there any possibility to write the Button once in a xml and then import it in all the layout I need it?
You can use
<include layout="#layout/commonlayout" android:id="#+id/id" />
commonlayout.xml should be defined in res/layout where you can add the repeated parts.
As Labeeb P rightly said, it works.
Just want to add that you can also override parameters too:
<include
layout="#layout/commonlayout"
android:id="#+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="2sp"
android:layout_marginRight="2sp"
/>
In addition to those great answers, you can also avoid code duplication by using the <merge> tag, like so:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/add"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/delete"/>
</merge>
The <merge> part gets stripped when you include it into other xml. This might help including more than a single Button at a time. See the official documentation.
You can use the default include XML tag to include an external layout:
<include layout="#layout/somelayout" />
This layout should have an outside ViewGroup that encapsulates the content or a merge tag to avoid having to use an unnecessary layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_world" />
</LinearLayout>
<!-- OR -->
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_world" />
</merge>
Also, if you need a better way to include pieces of layout that acts like a container (a custom ViewGroup), you can use this custom ViewGroup. Note that this does not import an XML into another XML file, it inflates the content from the external layout and replaces into the view. It's similar to ViewStub, a "ViewGroupStub" like.
This lib acts as if the ViewStub could be used as following (note that this example does not work! ViewStub isn't a ViewGroup subclass!):
<ViewStub layout="#layout/somecontainerlayout"
inflate_inside="#+id/somecontainerid">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_world" />
</ViewStub>

Categories

Resources