https://kotlinlang.org logo
#android
Title
# android
b

bhatnagarm

01/22/2020, 1:54 PM
@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

aipok

01/22/2020, 2:16 PM
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

bhatnagarm

01/23/2020, 3:47 AM
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

aipok

01/23/2020, 6:37 AM
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

bhatnagarm

01/23/2020, 6:43 AM
Yeah right default ones are must to be added. It worked then. Silly mistake. Thanks man
53 Views