1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.databinding.adapters;
17
18import android.databinding.BindingAdapter;
19import android.databinding.BindingMethod;
20import android.databinding.BindingMethods;
21import android.databinding.InverseBindingListener;
22import android.databinding.InverseBindingMethod;
23import android.databinding.InverseBindingMethods;
24import android.widget.CompoundButton;
25import android.widget.CompoundButton.OnCheckedChangeListener;
26
27@BindingMethods({
28        @BindingMethod(type = CompoundButton.class, attribute = "android:buttonTint", method = "setButtonTintList"),
29        @BindingMethod(type = CompoundButton.class, attribute = "android:onCheckedChanged", method = "setOnCheckedChangeListener"),
30})
31@InverseBindingMethods({
32        @InverseBindingMethod(type = CompoundButton.class, attribute = "android:checked"),
33})
34public class CompoundButtonBindingAdapter {
35
36    @BindingAdapter("android:checked")
37    public static void setChecked(CompoundButton view, boolean checked) {
38        if (view.isChecked() != checked) {
39            view.setChecked(checked);
40        }
41    }
42
43    @BindingAdapter(value = {"android:onCheckedChanged", "android:checkedAttrChanged"},
44            requireAll = false)
45    public static void setListeners(CompoundButton view, final OnCheckedChangeListener listener,
46            final InverseBindingListener attrChange) {
47        if (attrChange == null) {
48            view.setOnCheckedChangeListener(listener);
49        } else {
50            view.setOnCheckedChangeListener(new OnCheckedChangeListener() {
51                @Override
52                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
53                    if (listener != null) {
54                        listener.onCheckedChanged(buttonView, isChecked);
55                    }
56                    attrChange.onChange();
57                }
58            });
59        }
60    }
61
62}
63