问题
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.
回答1:
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.
回答2:
Finding a way using data-binding? Here is what I have done with test. First, create a custom binding adapter method:
@BindingAdapter({"app:customPrimaryBackground"})
public static void setCustomPrimaryBackground(View v, int resId) {
TypedValue typedValue = new TypedValue();
Context context = v.getContext();
if (resId == 0) {
context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
v.setBackgroundResource(typedValue.resourceId);
} else {
// Check the given resource ID is a color or drawable
context.getResources().getValue(resId, typedValue, true);
Drawable drawable;
if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// It's a color
drawable = new ColorDrawable(typedValue.data);
} else {
drawable = ContextCompat.getDrawable(context, resId);
}
v.setBackground(drawable);
}
}
Second, your binding xml layout:
<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"
app:customPrimaryBackground="@{toolBarBackgroundColor}"
/>
来源:https://stackoverflow.com/questions/31235519/data-binding-with-theme-attributes