In short you can use ViewBinding to replace findviewbyid() effectively. If your project is however more complex and you need to add features like binding data to views, binding adapters e.t.c, use DataBinding.
You just have to import <import type="android. content. Context" /> in your xml data imports. Then, you can access context for your databinding simply with context .
You can do this even simplier:
android:text= "@{@string/generic_text(profile.name)}"
you string should be like this:
<string name="generic_text">My Name is %s</string>
Edit:
Of course you can use as many variables as you need:
android:text= "@{@string/generic_text(profile.firstName, profile.secondName)}"
<string name="generic_text">My Name is %1$s %2$s</string>
It works just because it's designed in data binding. More in docs: https://developer.android.com/topic/libraries/data-binding/expressions#resources
You can do this:
android:text= "@{String.format(@string/Generic_Text, Profile.name)}"
if you use string formatting for your Generic_Text
string. ex. %s
at the end
android:text= "@{@string/generic_name(user.name)}"
Just make string resource like this.
<string name="generic_name">Hello %s</string>
android:text="@{`Hello ` + user.name}"/>
This is useful when you need hardcoded append like + for phone number.
String
's concat methodandroid:text="@{user.firstName.concat(@string/space).concat(user.lastName)}"
Here space
is an html entity which is placed inside strings.xml
. Because XML
does not accept Html entities or special characters directly. (Link Html Entities)
<string name="space">\u0020</string>
String.format()
android:text= "@{String.format(@string/Hello, user.name)}"
you have to import String class in layout in this type.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="String" />
</data>
<TextView
android:text= "@{String.format(@string/Hello, user.name)}"
... >
</TextView>
</layout>
android:text="@{@string/generic_name(user.firstName,user.lastName)}"
In this case put a string resource in strings.xml
<string name="generic_name">%1$s, %2$s</string>
There can be many other ways, choose one you need.
Use a Binding Adapter.
This sample is written in Kotlin and takes into account that the bound variable can be null:
@BindingAdapter("my_name")
fun TextView.setMyName(name: String?) {
this.text =
if (name.isNullOrEmpty()) "" else "${this.context.getString(R.string.Generic_Text)} $name"
}
then use the binding adapter in your XML instead of the android:text
property
app:my_name="@{Profile.name}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With