1 /*
2  * Copyright (C) 2006 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  */
16 
17 package android.widget;
18 
19 import android.annotation.IdRes;
20 import android.annotation.LayoutRes;
21 import android.content.Context;
22 import android.content.res.Resources;
23 import android.view.ContextThemeWrapper;
24 import android.view.View;
25 import android.view.ViewGroup;
26 import android.view.LayoutInflater;
27 import android.net.Uri;
28 
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Map;
32 
33 /**
34  * An easy adapter to map static data to views defined in an XML file. You can specify the data
35  * backing the list as an ArrayList of Maps. Each entry in the ArrayList corresponds to one row
36  * in the list. The Maps contain the data for each row. You also specify an XML file that
37  * defines the views used to display the row, and a mapping from keys in the Map to specific
38  * views.
39  *
40  * Binding data to views occurs in two phases. First, if a
41  * {@link android.widget.SimpleAdapter.ViewBinder} is available,
42  * {@link ViewBinder#setViewValue(android.view.View, Object, String)}
43  * is invoked. If the returned value is true, binding has occurred.
44  * If the returned value is false, the following views are then tried in order:
45  * <ul>
46  * <li> A view that implements Checkable (e.g. CheckBox).  The expected bind value is a boolean.
47  * <li> TextView.  The expected bind value is a string and {@link #setViewText(TextView, String)}
48  * is invoked.
49  * <li> ImageView. The expected bind value is a resource id or a string and
50  * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked.
51  * </ul>
52  * If no appropriate binding can be found, an {@link IllegalStateException} is thrown.
53  */
54 public class SimpleAdapter extends BaseAdapter implements Filterable, ThemedSpinnerAdapter {
55     private final LayoutInflater mInflater;
56 
57     private int[] mTo;
58     private String[] mFrom;
59     private ViewBinder mViewBinder;
60 
61     private List<? extends Map<String, ?>> mData;
62 
63     private int mResource;
64     private int mDropDownResource;
65 
66     /** Layout inflater used for {@link #getDropDownView(int, View, ViewGroup)}. */
67     private LayoutInflater mDropDownInflater;
68 
69     private SimpleFilter mFilter;
70     private ArrayList<Map<String, ?>> mUnfilteredData;
71 
72     /**
73      * Constructor
74      *
75      * @param context The context where the View associated with this SimpleAdapter is running
76      * @param data A List of Maps. Each entry in the List corresponds to one row in the list. The
77      *        Maps contain the data for each row, and should include all the entries specified in
78      *        "from"
79      * @param resource Resource identifier of a view layout that defines the views for this list
80      *        item. The layout file should include at least those named views defined in "to"
81      * @param from A list of column names that will be added to the Map associated with each
82      *        item.
83      * @param to The views that should display column in the "from" parameter. These should all be
84      *        TextViews. The first N views in this list are given the values of the first N columns
85      *        in the from parameter.
86      */
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, @LayoutRes int resource, String[] from, @IdRes int[] to)87     public SimpleAdapter(Context context, List<? extends Map<String, ?>> data,
88             @LayoutRes int resource, String[] from, @IdRes int[] to) {
89         mData = data;
90         mResource = mDropDownResource = resource;
91         mFrom = from;
92         mTo = to;
93         mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
94     }
95 
96     /**
97      * @see android.widget.Adapter#getCount()
98      */
getCount()99     public int getCount() {
100         return mData.size();
101     }
102 
103     /**
104      * @see android.widget.Adapter#getItem(int)
105      */
getItem(int position)106     public Object getItem(int position) {
107         return mData.get(position);
108     }
109 
110     /**
111      * @see android.widget.Adapter#getItemId(int)
112      */
getItemId(int position)113     public long getItemId(int position) {
114         return position;
115     }
116 
117     /**
118      * @see android.widget.Adapter#getView(int, View, ViewGroup)
119      */
getView(int position, View convertView, ViewGroup parent)120     public View getView(int position, View convertView, ViewGroup parent) {
121         return createViewFromResource(mInflater, position, convertView, parent, mResource);
122     }
123 
createViewFromResource(LayoutInflater inflater, int position, View convertView, ViewGroup parent, int resource)124     private View createViewFromResource(LayoutInflater inflater, int position, View convertView,
125             ViewGroup parent, int resource) {
126         View v;
127         if (convertView == null) {
128             v = inflater.inflate(resource, parent, false);
129         } else {
130             v = convertView;
131         }
132 
133         bindView(position, v);
134 
135         return v;
136     }
137 
138     /**
139      * <p>Sets the layout resource to create the drop down views.</p>
140      *
141      * @param resource the layout resource defining the drop down views
142      * @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
143      */
setDropDownViewResource(int resource)144     public void setDropDownViewResource(int resource) {
145         mDropDownResource = resource;
146     }
147 
148     /**
149      * Sets the {@link android.content.res.Resources.Theme} against which drop-down views are
150      * inflated.
151      * <p>
152      * By default, drop-down views are inflated against the theme of the
153      * {@link Context} passed to the adapter's constructor.
154      *
155      * @param theme the theme against which to inflate drop-down views or
156      *              {@code null} to use the theme from the adapter's context
157      * @see #getDropDownView(int, View, ViewGroup)
158      */
159     @Override
setDropDownViewTheme(Resources.Theme theme)160     public void setDropDownViewTheme(Resources.Theme theme) {
161         if (theme == null) {
162             mDropDownInflater = null;
163         } else if (theme == mInflater.getContext().getTheme()) {
164             mDropDownInflater = mInflater;
165         } else {
166             final Context context = new ContextThemeWrapper(mInflater.getContext(), theme);
167             mDropDownInflater = LayoutInflater.from(context);
168         }
169     }
170 
171     @Override
getDropDownViewTheme()172     public Resources.Theme getDropDownViewTheme() {
173         return mDropDownInflater == null ? null : mDropDownInflater.getContext().getTheme();
174     }
175 
176     @Override
getDropDownView(int position, View convertView, ViewGroup parent)177     public View getDropDownView(int position, View convertView, ViewGroup parent) {
178         final LayoutInflater inflater = mDropDownInflater == null ? mInflater : mDropDownInflater;
179         return createViewFromResource(inflater, position, convertView, parent, mDropDownResource);
180     }
181 
bindView(int position, View view)182     private void bindView(int position, View view) {
183         final Map dataSet = mData.get(position);
184         if (dataSet == null) {
185             return;
186         }
187 
188         final ViewBinder binder = mViewBinder;
189         final String[] from = mFrom;
190         final int[] to = mTo;
191         final int count = to.length;
192 
193         for (int i = 0; i < count; i++) {
194             final View v = view.findViewById(to[i]);
195             if (v != null) {
196                 final Object data = dataSet.get(from[i]);
197                 String text = data == null ? "" : data.toString();
198                 if (text == null) {
199                     text = "";
200                 }
201 
202                 boolean bound = false;
203                 if (binder != null) {
204                     bound = binder.setViewValue(v, data, text);
205                 }
206 
207                 if (!bound) {
208                     if (v instanceof Checkable) {
209                         if (data instanceof Boolean) {
210                             ((Checkable) v).setChecked((Boolean) data);
211                         } else if (v instanceof TextView) {
212                             // Note: keep the instanceof TextView check at the bottom of these
213                             // ifs since a lot of views are TextViews (e.g. CheckBoxes).
214                             setViewText((TextView) v, text);
215                         } else {
216                             throw new IllegalStateException(v.getClass().getName() +
217                                     " should be bound to a Boolean, not a " +
218                                     (data == null ? "<unknown type>" : data.getClass()));
219                         }
220                     } else if (v instanceof TextView) {
221                         // Note: keep the instanceof TextView check at the bottom of these
222                         // ifs since a lot of views are TextViews (e.g. CheckBoxes).
223                         setViewText((TextView) v, text);
224                     } else if (v instanceof ImageView) {
225                         if (data instanceof Integer) {
226                             setViewImage((ImageView) v, (Integer) data);
227                         } else {
228                             setViewImage((ImageView) v, text);
229                         }
230                     } else {
231                         throw new IllegalStateException(v.getClass().getName() + " is not a " +
232                                 " view that can be bounds by this SimpleAdapter");
233                     }
234                 }
235             }
236         }
237     }
238 
239     /**
240      * Returns the {@link ViewBinder} used to bind data to views.
241      *
242      * @return a ViewBinder or null if the binder does not exist
243      *
244      * @see #setViewBinder(android.widget.SimpleAdapter.ViewBinder)
245      */
getViewBinder()246     public ViewBinder getViewBinder() {
247         return mViewBinder;
248     }
249 
250     /**
251      * Sets the binder used to bind data to views.
252      *
253      * @param viewBinder the binder used to bind data to views, can be null to
254      *        remove the existing binder
255      *
256      * @see #getViewBinder()
257      */
setViewBinder(ViewBinder viewBinder)258     public void setViewBinder(ViewBinder viewBinder) {
259         mViewBinder = viewBinder;
260     }
261 
262     /**
263      * Called by bindView() to set the image for an ImageView but only if
264      * there is no existing ViewBinder or if the existing ViewBinder cannot
265      * handle binding to an ImageView.
266      *
267      * This method is called instead of {@link #setViewImage(ImageView, String)}
268      * if the supplied data is an int or Integer.
269      *
270      * @param v ImageView to receive an image
271      * @param value the value retrieved from the data set
272      *
273      * @see #setViewImage(ImageView, String)
274      */
setViewImage(ImageView v, int value)275     public void setViewImage(ImageView v, int value) {
276         v.setImageResource(value);
277     }
278 
279     /**
280      * Called by bindView() to set the image for an ImageView but only if
281      * there is no existing ViewBinder or if the existing ViewBinder cannot
282      * handle binding to an ImageView.
283      *
284      * By default, the value will be treated as an image resource. If the
285      * value cannot be used as an image resource, the value is used as an
286      * image Uri.
287      *
288      * This method is called instead of {@link #setViewImage(ImageView, int)}
289      * if the supplied data is not an int or Integer.
290      *
291      * @param v ImageView to receive an image
292      * @param value the value retrieved from the data set
293      *
294      * @see #setViewImage(ImageView, int)
295      */
setViewImage(ImageView v, String value)296     public void setViewImage(ImageView v, String value) {
297         try {
298             v.setImageResource(Integer.parseInt(value));
299         } catch (NumberFormatException nfe) {
300             v.setImageURI(Uri.parse(value));
301         }
302     }
303 
304     /**
305      * Called by bindView() to set the text for a TextView but only if
306      * there is no existing ViewBinder or if the existing ViewBinder cannot
307      * handle binding to a TextView.
308      *
309      * @param v TextView to receive text
310      * @param text the text to be set for the TextView
311      */
setViewText(TextView v, String text)312     public void setViewText(TextView v, String text) {
313         v.setText(text);
314     }
315 
getFilter()316     public Filter getFilter() {
317         if (mFilter == null) {
318             mFilter = new SimpleFilter();
319         }
320         return mFilter;
321     }
322 
323     /**
324      * This class can be used by external clients of SimpleAdapter to bind
325      * values to views.
326      *
327      * You should use this class to bind values to views that are not
328      * directly supported by SimpleAdapter or to change the way binding
329      * occurs for views supported by SimpleAdapter.
330      *
331      * @see SimpleAdapter#setViewImage(ImageView, int)
332      * @see SimpleAdapter#setViewImage(ImageView, String)
333      * @see SimpleAdapter#setViewText(TextView, String)
334      */
335     public static interface ViewBinder {
336         /**
337          * Binds the specified data to the specified view.
338          *
339          * When binding is handled by this ViewBinder, this method must return true.
340          * If this method returns false, SimpleAdapter will attempts to handle
341          * the binding on its own.
342          *
343          * @param view the view to bind the data to
344          * @param data the data to bind to the view
345          * @param textRepresentation a safe String representation of the supplied data:
346          *        it is either the result of data.toString() or an empty String but it
347          *        is never null
348          *
349          * @return true if the data was bound to the view, false otherwise
350          */
setViewValue(View view, Object data, String textRepresentation)351         boolean setViewValue(View view, Object data, String textRepresentation);
352     }
353 
354     /**
355      * <p>An array filters constrains the content of the array adapter with
356      * a prefix. Each item that does not start with the supplied prefix
357      * is removed from the list.</p>
358      */
359     private class SimpleFilter extends Filter {
360 
361         @Override
performFiltering(CharSequence prefix)362         protected FilterResults performFiltering(CharSequence prefix) {
363             FilterResults results = new FilterResults();
364 
365             if (mUnfilteredData == null) {
366                 mUnfilteredData = new ArrayList<Map<String, ?>>(mData);
367             }
368 
369             if (prefix == null || prefix.length() == 0) {
370                 ArrayList<Map<String, ?>> list = mUnfilteredData;
371                 results.values = list;
372                 results.count = list.size();
373             } else {
374                 String prefixString = prefix.toString().toLowerCase();
375 
376                 ArrayList<Map<String, ?>> unfilteredValues = mUnfilteredData;
377                 int count = unfilteredValues.size();
378 
379                 ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);
380 
381                 for (int i = 0; i < count; i++) {
382                     Map<String, ?> h = unfilteredValues.get(i);
383                     if (h != null) {
384 
385                         int len = mTo.length;
386 
387                         for (int j=0; j<len; j++) {
388                             String str =  (String)h.get(mFrom[j]);
389 
390                             String[] words = str.split(" ");
391                             int wordCount = words.length;
392 
393                             for (int k = 0; k < wordCount; k++) {
394                                 String word = words[k];
395 
396                                 if (word.toLowerCase().startsWith(prefixString)) {
397                                     newValues.add(h);
398                                     break;
399                                 }
400                             }
401                         }
402                     }
403                 }
404 
405                 results.values = newValues;
406                 results.count = newValues.size();
407             }
408 
409             return results;
410         }
411 
412         @Override
publishResults(CharSequence constraint, FilterResults results)413         protected void publishResults(CharSequence constraint, FilterResults results) {
414             //noinspection unchecked
415             mData = (List<Map<String, ?>>) results.values;
416             if (results.count > 0) {
417                 notifyDataSetChanged();
418             } else {
419                 notifyDataSetInvalidated();
420             }
421         }
422     }
423 }
424