我想知道如何对此适配器进行排序:
private class ProductsListAdapter extends BaseAdapter {
public ProductsListAdapter() {
super();
}
public int getCount() {
return SingletonComparer.getInstance().getProducts().size();
}
public Object getItem(int position) {
return SingletonComparer.getInstance().getProducts().get(position);
}
public long getItemId(int position) {
return SingletonComparer.getInstance().getProducts().get(position).getId();
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(SingletonComparer.getInstance().getProducts().get(position)
.getName());
TextView textView2 = getGenericView();
textView2.setText(""
+ SingletonComparer.getInstance().getProducts()
.get(position).getPrice());
TextView textView3 = getGenericView();
textView3.setText(SingletonData.getInstance().getBrandName(SingletonComparer.getInstance().getProducts().get(position)
.getBrandID()));
LinearLayout ll = new LinearLayout(getActivity());
ll.addView(textView, new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f));
ll.addView(textView2, 1, new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f));
ll.addView(textView3, 2, new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f));
ll.setId(SingletonComparer.getInstance().getProducts().get(position)
.getId());
return ll;
}
}
按字段
SingletonComparer.getInstance().getProducts()
.get(position).getPrice());
这可能吗?如果是的我怎么能这样做?
答案 0 :(得分:9)
您可以使用比较器对列出的项目进行排序。
你可以这样做:
public class SortByPrice implements Comparator{
public int compare(Object o1, Object o2) {
Product p1 = (Product) o1;
Product p2 = (Product) o2;
// return -1, 0, 1 to determine less than, equal to or greater than
return (p1.getPrice() > p2.getPrice() ? 1 : (p1.getPrice() == p2.getPrice() ? 0 : -1));
// **or** the previous return statement can be simplified to:
return p1.getPrice() - p2.getPrice();
}
}
您不希望在getView()
方法中执行此操作,而是在将数据添加到适配器时通过对列表进行排序来执行此操作,因此它在从一开始就订购。
因此,在将数据添加到列表之前,请致电:
Collections.sort(list, new SortByPrice());
将使用您创建的比较器对数据进行排序。
答案 1 :(得分:1)
您无法对适配器进行排序。您应该对数据源进行排序(我期望在SingletonComparer
类中处理)
BTW:你应该重构代码,在适配器成员中存储对SingletonComparer
的引用,而不是继续执行SingletonComparer.getInstance().getProducts()
。