@here Is it possible to set layout_height or layou...
# android
b
@here Is it possible to set layout_height or layout_width for a view using data binding. Tried SO but didn't work.
google 1
stackoverflow 1
a
This could be achived using BindingAdapter with enum as parameter, that you can choise which width/height to use. Something like this:
Copy code
@BindingAdapter("dynamic_width")
fun View.setWidth(layoutParams: LayoutParams) {
    this.layoutParams.width = when(layoutParams) {
        LayoutParams.wrapContent -> ViewGroup.LayoutParams.WRAP_CONTENT
        LayoutParams.matchParent -> ViewGroup.LayoutParams.MATCH_PARENT
    }
}

@BindingAdapter("dynamic_height")
fun View.setHeight(layoutParams: LayoutParams) {
    this.layoutParams.height = when(layoutParams) {
        LayoutParams.wrapContent -> ViewGroup.LayoutParams.WRAP_CONTENT
        LayoutParams.matchParent -> ViewGroup.LayoutParams.MATCH_PARENT
    }
}

enum class LayoutParams{
    wrapContent, matchParent
}
Usage will be like this:
Copy code
app:dynamic_width="@{someCondition ? matchParent: wrapContent}"
b
Thanks @aipok for the quick reply and code snippet. Have already tried this out, unfortunately it didn't work
So let's go this way
If I don't specifically mention either of android:layout_height or android:layout_width
And rather use the static binding to set either of these
They're is compile time error that says that either height or width is missing
a
you should still set the regular
android:layout_width="wrap_content"
and
android:layout_height="wrap_content"
or whatever value is good to set as default for you and after that the BindingAdapter will override it. I'm sure this is working. As you saw probably for dynamic height example (at google data biunding article), you should define the default width and height, since they are required. And data binding executed later.
b
Yeah right default ones are must to be added. It worked then. Silly mistake. Thanks man