I am trying out the new Android Databinding Library and I wanted to set the background color of ToolBar using a binding. By default the color should be colorPrimary (from the theme).
Before I was using DataBinding, my toolBar looked like
<android.support.v7.widget.Toolbar android:id="@+id/mainToolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" />
After adding a binding, I wanted to set its background to colorPrimary if no color is bound - I'm using ternary operator for this (as mentioned in the guide) - but it causes an error, as theme attributes also have a "?" operator before their names. The compiler thinks I'm starting a new ternary operation.
<data> <variable name="toolBarBackgroundColor" type="int"/> </data> ... <android.support.v7.widget.Toolbar android:id="@+id/mainToolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@{toolBarBackgroundColor!=0? toolBarBackgroundColor: ?attr/colorPrimary }" />
So is there a way I can access theme attributes inside a binding operation? Thanks!
Edit
I know I can get the colorPrimary attribute programmatically and bind it through java code. But I'm just wondering if there's an Xml-based solution for this or not.
Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.
Android Studio Supports Data BindingSyntax Highlighting. XML code completion. Flagging of expression language syntax errors. Navigate to declaration.
Data binding includes everything that ViewBinding has, so it wasn't designed to work side by side with View binding. The biggest issue is the naming conflict between the generated classes. Both ViewBinding and DataBonding would want to generate the class MainLayoutBinding for the layout main_layout. xml .
The answer is a bit late, but maybe it helps someone.
For accessing theme attributes in data binding, you can use this:
(imagine that clickable
is Boolean
variable)
android:background="@{clickable ? android.R.attr.selectableItemBackground : android.R.color.transparent}"
No additional binding adapters or another things needed.
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