在android开发中SimpleAdapter很常用的类,但是它只适合静态的数据,不方便去动态改变数据,在它的文档中我们可以看到第一句话是这么写的An easy adapter to map static data to views defined in an XML file. 所以它只适合绑定静态的数据。我们可以通过操作初始化Adapter时的List参数,去添加,删除数据,然后调用适配器的notifyDataSetChanged()方法来改变数据的显示,简单的需求这么实现没什么问题,其实这么做不太科学,首先是它有点违背适配器模式的设计思想,还有重要的是不安全,在复杂环境中出现多线程操作,或者要对数据排序,调用Filter过滤数据都会出现问题,看源码可以看出在调用Filter过滤数据时它会将原始数据保存一个备份,然后将过滤后的数据重新复制给当时传参进来的List,这是你操作的那个List就会失效。
android中还有一个自带适配器ArrayAdapter,它支持动态的改变数据,可以看到add,remove,insert,clear等方法,但是它默认只适合简单的数据,他自动绑定的数据只有一个字符串到一个TextView,要想实现复杂数据就要重写getView()方法。我在开发中遇到的很多情况都是调用接口得到JSON数据,再将JSON数据转化成List<Map<String, Object>>对象,所以我选择自定义SimpleAdapter,其实就是数据操作用ArrayAdapter中的方法而getView用SimpleApapter中的方法,写出来的代码如下
不知道为什么Android没有这么去实现,这样实现有什么不妥之处吗?
这里我自己实现了一个排序方法,根据Map中value字符串顺序去排序
做了几个项目感觉都大同小异,所以记录下来方便以后使用
本人初学android,有什么错误,或者有更好的方法,欢迎指正
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class MySimpleAdapter<T extends Map<String, ?>> extends BaseAdapter implements Filterable {
private int[] mTo;
private String[] mFrom;
private List<T> mData;
private int mResource;
private LayoutInflater mInflater;
private SimpleFilter mFilter;
private ArrayList<T> mUnfilteredData;
/**
* 用于修改内容{@link #mData}的锁。在数组中执行任何写操作都要用这个锁来做同步。这个锁
* 还被用在过滤器(see {@link #getFilter()}建立一个同步的原始数据副本。
*/
private final Object mLock = new Object();
/**
* 当{@link #mData}被修改后是否 调用{@link #notifyDataSetChanged()}。
*/
private boolean mNotifyOnChange = true;
/**
* 构造器
*
* @param context The context where the View associated with this OrderListAdapter is running
* @param data A List of Maps. Each entry in the List corresponds to one row in the list. The
* Maps contain the data for each row, and should include all the entries specified in
* "from"
* @param resource Resource identifier of a view layout that defines the views for this list
* item. The layout file should include at least those named views defined in "to"
* @param from A list of column names that will be added to the Map associated with each
* item.
* @param to The views that should display column in the "from" parameter. These should all be
* TextViews. The first N views in this list are given the values of the first N columns
* in the from parameter.
*/
public OrderListAdapter(Context context, List<T> data,
int resource, String[] from, int[] to) {
mData = data;
mResource = resource;
mFrom = from;
mTo = to;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* Adds the specified object at the end of the array.
*
* @param object The object to add at the end of the array.
*/
public void add(T object) {
synchronized (mLock) {
if (mUnfilteredData != null) {
mUnfilteredData.add(object);
} else {
mData.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Adds the specified Collection at the end of the array.
*
* @param collection The Collection to add at the end of the array.
*/
public void addAll(Collection<? extends T> collection) {
synchronized (mLock) {
if (mUnfilteredData != null) {
mUnfilteredData.addAll(collection);
} else {
mData.addAll(collection);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Adds the specified items at the end of the array.
*
* @param items The items to add at the end of the array.
*/
public void addAll(T ... items) {
synchronized (mLock) {
if (mUnfilteredData != null) {
Collections.addAll(mUnfilteredData, items);
} else {
Collections.addAll(mData, items);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Inserts the specified object at the specified index in the array.
*
* @param object The object to insert into the array.
* @param index The index at which the object must be inserted.
*/
public void insert(T object, int index) {
synchronized (mLock) {
if (mUnfilteredData != null) {
mUnfilteredData.add(index, object);
} else {
mData.add(index, object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Removes the specified object from the array.
*
* @param object The object to remove.
*/
public void remove(T object) {
synchronized (mLock) {
if (mUnfilteredData != null) {
mUnfilteredData.remove(object);
} else {
mData.remove(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Remove all elements from the list.
*/
public void clear() {
synchronized (mLock) {
if (mUnfilteredData != null) {
mUnfilteredData.clear();
} else {
mData.clear();
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Control whether methods that change the list ({@link #add},
* {@link #insert}, {@link #remove}, {@link #clear}) automatically call
* {@link #notifyDataSetChanged}. If set to false, caller must
* manually call notifyDataSetChanged() to have the changes
* reflected in the attached view.
*
* The default is true, and calling notifyDataSetChanged()
* resets the flag to true.
*
* @param notifyOnChange if true, modifications to the list will
* automatically call {@link
* #notifyDataSetChanged}
*/
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
/**
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return mData.size();
}
/**
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return mData.get(position);
}
/**
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
/**
* @see android.widget.Adapter#getView(int, View, ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
return createViewFromResource(position, convertView, parent, mResource);
}
private View createViewFromResource(int position, View convertView,
ViewGroup parent, int resource) {
View v;
if (convertView == null) {
v = mInflater.inflate(resource, parent, false);
} else {
v = convertView;
}
bindView(position, v);
return v;
}
private void bindView(int position, View view) {
final T dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null||data==JSONObject.NULL ? "" : data.toString();
if (text == null) {
text = "";
}
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this OrderListAdapter");
}
}
}
}
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* This method is called instead of {@link #setViewImage(ImageView, String)}
* if the supplied data is an int or Integer.
*
* @param v ImageView to receive an image
* @param value the value retrieved from the data set
*
* @see #setViewImage(ImageView, String)
*/
public void setViewImage(ImageView v, int value) {
v.setImageResource(value);
}
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {@link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* @param v ImageView to receive an image
* @param value the value retrieved from the data set
*
* @see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
/**
* Called by bindView() to set the text for a TextView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to a TextView.
*
* @param v TextView to receive text
* @param text the text to be set for the TextView
*/
public void setViewText(TextView v, String text) {
v.setText(text);
}
public Filter getFilter() {
if (mFilter == null) {
mFilter = new SimpleFilter();
}
return mFilter;
}
/**
* 按照给定的列和顺序对适配器中的数据排序
* @param row 列数
* @param order true代表从小到大,false代表从大到小
*/
public void sort(int row, boolean order){
sort(mFrom[row], order);
}
/**
* 按照给定的列和顺序对适配器中的数据排序
* @param key Map中的key值
* @param order true代表从小到大,false代表从大到小
*/
public void sort(String key, boolean order){
synchronized (mLock) {
Collections.sort(mData, new OrderListComparator(key, order));
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* <p>An array filters constrains the content of the array adapter with
* a prefix. Each item that does not start with the supplied prefix
* is removed from the list.</p>
*/
private class SimpleFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mUnfilteredData == null) {
synchronized (mLock) {
mUnfilteredData = new ArrayList<T>(mData);
}
}
if (prefix == null || prefix.length() == 0) {
ArrayList<T> list;
synchronized (mLock) {
list = new ArrayList<T>(mUnfilteredData);
}
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
ArrayList<T> unfilteredValues;
synchronized (mLock) {
unfilteredValues = new ArrayList<T>(mUnfilteredData);
}
int count = unfilteredValues.size();
ArrayList<T> newValues = new ArrayList<T>(count);
for (int i = 0; i < count; i++) {
T h = unfilteredValues.get(i);
if (h != null) {
int len = mTo.length;
for (int j=0; j<len; j++) {
Object obj = h.get(mFrom[j]);
String str = obj==null?"":obj.toString();
String[] words = str.split(" ");
int wordCount = words.length;
for (int k = 0; k < wordCount; k++) {
String word = words[k];
if (word.toLowerCase().startsWith(prefixString)) {
newValues.add(h);
break;
}
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mData = (List<T>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
private class OrderListComparator implements Comparator<T>{
private String key;
private boolean order;
public OrderListComparator(String key, boolean order) {
super();
this.key = key;
this.order = order;
}
@Override
public int compare(T lhs, T rhs) {
Object lhsobj = lhs.get(key);
Object rhsobj = rhs.get(key);
String lhsstr = lhsobj==null||lhsobj==JSONObject.NULL?"":lhsobj.toString();
String rhsstr = rhsobj==null||rhsobj==JSONObject.NULL?"":rhsobj.toString();
int result = lhsstr.compareTo(rhsstr);
return order?result:-result;
}
}
}