Reputation: 58944
I want to set a view visibility dependent on a CheckBox checked status. Something like we do in preference.xml.
Currently i am doing
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
>
<data>
<import type="android.view.View"/>
<variable
name="isScheduleChecked"
type="java.lang.Boolean"/>
<variable
name="activity"
type="com.amelio.ui.activities.ActivityCart"/>
</data>
<LinearLayout
style="@style/llDefault"
android:layout_height="match_parent"
android:orientation="vertical"
>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onCheckedChanged="@{()-> isScheduleChecked}"
android:text="Checkbox"/>
<LinearLayout
style="@style/llDefault"
android:padding="@dimen/space_small"
android:visibility="@{isScheduleChecked ? View.VISIBLE : View.GONE, default = gone}"
>
</LinearLayout>
</LinearLayout>
</layout>
This does not work. I think android:onCheckedChanged="@{()-> isScheduleChecked}"
this line is not working. What i am doing wrong? Some tell me best way to implement it.
Currently i am changing isScheduleChecked by my activity in java code like binding.setIsScheduleChecked(true/false);
but i don't to write code in java class for just set visibility.
Upvotes: 7
Views: 5271
Reputation: 41
For those who have tried Khemraj Sharma's solution and not worked, you may try this as it works for me.
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Checkbox"/>
<LinearLayout
style="@style/llDefault"
android:padding="@dimen/space_small"
android:visibility="@{checkbox.checked ? View.VISIBLE : View.GONE, default = gone}">
</LinearLayout>
From Khemraj Sharma's solution, what I have modified is the data binding part. I have changed it
From:
@{checkbox.isChecked() ? View.VISIBLE : View.GONE, default = gone}
To:
@{checkbox.checked ? View.VISIBLE : View.GONE, default = gone}
"checked" should be used instead of "isChecked()" as "isChecked()" doesn't work for me.
Upvotes: 2
Reputation: 58944
You can refer to id in data binding. No need to take another variable.
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Checkbox"/>
<LinearLayout
style="@style/llDefault"
android:padding="@dimen/space_small"
android:visibility="@{checkbox.isChecked() ? View.VISIBLE : View.GONE, default = gone}"
>
</LinearLayout>
camelCase
. like id is check_box
then you will use checkBox.isChecked()
.You must import View
in layout to use it View.VISIBLE
<data>
<import type="android.view.View"/>
</data>
If you are having any other issue then you can comment.
Upvotes: 7
Reputation: 472
That's a cool idea! I got it to work by replacing your onCheckedChanged
line with:
android:checked="@={isScheduleChecked}"
Upvotes: 5