AbsSpinnerBindingAdapter.java revision 10960eb5f73fd587c2f8d18cfc61873c04017512
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.widget.AbsSpinner;
20import android.widget.ArrayAdapter;
21import android.widget.SpinnerAdapter;
22
23public class AbsSpinnerBindingAdapter {
24
25    @BindingAdapter({"android:entries"})
26    public static void setEntries(AbsSpinner view, CharSequence[] entries) {
27        if (entries != null) {
28            SpinnerAdapter oldAdapter = view.getAdapter();
29            boolean changed = true;
30            if (oldAdapter != null && oldAdapter.getCount() == entries.length) {
31                changed = false;
32                for (int i = 0; i < entries.length; i++) {
33                    if (!entries[i].equals(oldAdapter.getItem(i))) {
34                        changed = true;
35                        break;
36                    }
37                }
38            }
39            if (changed) {
40                ArrayAdapter<CharSequence> adapter =
41                        new ArrayAdapter<CharSequence>(view.getContext(),
42                                android.R.layout.simple_spinner_item, entries);
43                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
44                view.setAdapter(adapter);
45            }
46        } else {
47            view.setAdapter(null);
48        }
49    }
50}
51