androidandroid-layoutdata-bindingandroid-attributes

Is there a way to read a view attribute via databinding during view creation?


I'm using databinding and I'm trying to compose some settings. I have a view whose layout I want to be determined via a custom attribute (passing in an enum). For example passing in either Setting.CHECKBOX or Setting.SWITCH should let me inflate the appropriate control for the view. The view would be defined like this:

<data>
<import type="com.mypackage.ui.SettingView.SettingControl" />

<SettingView
    android:id="@+id/setting_foo
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    setting:control="@{Setting.CHECKBOX} />
...

Is there a way I can read that setting:control attribute before the layout is inflated? Based on the setting, I want to specify how to inflate the SettingView.

I know I can do it via custom attributes/styleables, but I was wondering if it could be achieved via databinding.


Solution

  • No. In order to look at the attribute value during inflation, you can't use data binding syntax. Data binding will strip the value from the XML and add it to the generated binding code.

    Instead, add the attribute to the attrs.xml file and assign the value using the normal syntax. You can then read the attribute using context.obtainedStyledAttributes() and accessing the value through the TypedArray.