Data binding gives you everything that view binding does. So, if you have enabled data binding for the project, just use data binding. " seems kind of silly to have even created viewBinding after data binding has already been established" -- it is a matter of build performance.
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 .
There is no need to import the String class into your layout file. To check whether two strings have equal value or not equals() method should be used. = is used to check the whether the two strings refer to the same reference object or not.
Another solution is to create a custom @BindingAdapter
for it.
@BindingAdapter({"format", "argId"})
public static void setFormattedText(TextView textView, String format, int argId){
if(argId == 0) return;
textView.setText(String.format(format, textView.getResources().getString(argId)));
}
And then just provide the variables separately.
<TextView
app:format="@{@string/myFormatString}"
app:argId="@{myPojo.resourceId}"
You could use an array if you need multiple arguments, but in my case, one was sufficient.
As of June 2016 this is possible in XML:
android:text= "@{String.format(@string/my_format_string, myPojo.resourceId)}"
You can use:
android:text='@{(id > 0) ? context.getString(id) : ""}'
I ended up creating my own method:
public class BindingUtils {
public static String string(int resourceId) {
return MyApplication
.getApplication()
.getResources()
.getString(resourceId);
}
}
Declaring an import for it:
<data>
<import type="com.example.BindingUtils" />
...
</data>
And just calling it during binding:
android:text="@{@string/myFormatString(BindingUtils.string(myPojo.resourceId))}"
Would be nice to have out-of-the-box method for that. DataBinding is sitll in Beta - so maybe it will come in future.
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