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