使用Comparator和Custom ArrayAdapter使用对象对ArrayList进行排序

时间:2015-02-05 10:37:06

标签: android sorting arraylist android-arrayadapter comparator

如何使用Comparator正确排序对象的ArrayList,然后将此已排序的数组传递给自定义数组适配器?

我试过这样:

ArrayList的内容类:

public class CoursesData {
private String url;
private String name;
private String lessonsCount;
private String isFree;
private String price;
private String language;
private String difficulty;

private AuthorData author;

.....getters-setters
}

比较

class CoursesPriceComparator implements Comparator <CoursesData> {
public int compare (CoursesData left, CoursesData right){
    return left.getPrice().compareTo(right.getPrice());
}
}

在OnCreate中设置适配器:

        mAdapter = new CoursesItemAdapter(getActivity(),
            R.layout.catalog_list_item,
            Collections.sort(parserJson.getCourses(), new CoursesPriceComparator()));

..并在此处收到错误: enter image description here

...因为我正在使用自定义ArrayAdapter,如:

class CoursesItemAdapter extends ArrayAdapter<CoursesData> {
private Activity myContext;
private ArrayList<CoursesData> datas;

public CoursesItemAdapter(Context context, int textViewResourceId, ArrayList<CoursesData> objects){
    super(context, textViewResourceId, objects);

    myContext = (Activity) context;
    datas = objects;
}

public View getView(int position, View convertView, ViewGroup parent){
    ViewHolder viewHolder;

    if(convertView == null) {
        LayoutInflater inflater = myContext.getLayoutInflater();
        convertView = inflater.inflate(R.layout.catalog_list_item, null);

        viewHolder = new ViewHolder();
        viewHolder.postNameView = (TextView) convertView.findViewById(R.id.courses_name);
        viewHolder.postDifficultyView = (TextView) convertView.findViewById(R.id.difficulty);
        viewHolder.postAuthorView = (TextView) convertView.findViewById(R.id.author);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }


    viewHolder.postNameView.setText(datas.get(position).getName());
    viewHolder.postAuthorView.setText(datas.get(position).getAuthor().getName());
    viewHolder.postDifficultyView.setText(datas.get(position).getDifficulty());

    return convertView;
}
    static class ViewHolder{
    TextView postNameView;
    TextView postAuthorView;
    TextView postDifficultyView;
}

如何修改此适配器以使其与Comparable一起使用?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您假设Collections.sort(返回已排序的集合是错误的。

mAdapter = new CoursesItemAdapter(getActivity(),
            R.layout.catalog_list_item,
            Collections.sort(parserJson.getCourses(), new CoursesPriceComparator()));

应该是

ArrayList< CoursesData > data = parserJson.getCourses();
Collections.sort(parserJson.getCourses(), new CoursesPriceComparator())
mAdapter = new CoursesItemAdapter(getActivity(),
            R.layout.catalog_list_item,
            data);

Collection.sort返回类型无效。点击此处documentation