Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Binding with theme attributes

Tags:

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.

like image 802
sudo_rizwan Avatar asked Jul 05 '15 22:07

sudo_rizwan


People also ask

What is data binding with example?

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.

Which of the following is included in data binding?

Android Studio Supports Data BindingSyntax Highlighting. XML code completion. Flagging of expression language syntax errors. Navigate to declaration.

Can I use both data binding and view binding?

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 .


1 Answers

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.

like image 144
tikhonos Avatar answered Oct 07 '22 01:10

tikhonos