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 23import java.util.List; 24 25public class AbsSpinnerBindingAdapter { 26 27 @BindingAdapter({"android:entries"}) 28 public static <T extends CharSequence> void setEntries(AbsSpinner view, T[] entries) { 29 if (entries != null) { 30 SpinnerAdapter oldAdapter = view.getAdapter(); 31 boolean changed = true; 32 if (oldAdapter != null && oldAdapter.getCount() == entries.length) { 33 changed = false; 34 for (int i = 0; i < entries.length; i++) { 35 if (!entries[i].equals(oldAdapter.getItem(i))) { 36 changed = true; 37 break; 38 } 39 } 40 } 41 if (changed) { 42 ArrayAdapter<CharSequence> adapter = 43 new ArrayAdapter<CharSequence>(view.getContext(), 44 android.R.layout.simple_spinner_item, entries); 45 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 46 view.setAdapter(adapter); 47 } 48 } else { 49 view.setAdapter(null); 50 } 51 } 52 53 @BindingAdapter({"android:entries"}) 54 public static <T> void setEntries(AbsSpinner view, List<T> entries) { 55 if (entries != null) { 56 SpinnerAdapter oldAdapter = view.getAdapter(); 57 if (oldAdapter instanceof ObservableListAdapter) { 58 ((ObservableListAdapter) oldAdapter).setList(entries); 59 } else { 60 view.setAdapter(new ObservableListAdapter<T>(view.getContext(), entries, 61 android.R.layout.simple_spinner_item, 62 android.R.layout.simple_spinner_dropdown_item, 0)); 63 } 64 } else { 65 view.setAdapter(null); 66 } 67 } 68} 69