我正在尝试按字母顺序对我添加到ListView中的元素进行排序,使用Comparable java接口及其方法Compareto()。
所以这是我实现的适配器的代码:我尝试在addLocation()中使用Collections.sort方法。
您可以在this post
上查看我项目的其他文件
public class LocationAdapter extends BaseAdapter {
private List<Location> Locations;
int monLayout;
LayoutInflater inflater;
public LocationAdapter(Context context, int layout){
monLayout=layout;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Locations = new ArrayList<Location>();
}
private class Location implements Comparable{
public String name;
public String address;
public Long date;
public Location(String _name,String _address , Long _date){
name=_name;
address=_address;
date=_date;
}
@Override
public int compareTo(Object another) {
int res;
Location loc=(Location)another;
char firstLetter = loc.name.charAt(0);
char thisFirstLetter = this.name.charAt(0);
if(thisFirstLetter<firstLetter){
res=1;
}
else if(thisFirstLetter<firstLetter){
res=-1;
}
else
{
res=0;
}
return res;
}
}
private class ViewHolder{
TextView name_view;
TextView address_view;
TextView date_view;
public ViewHolder(View rowLayout){
name_view = (TextView)rowLayout.findViewById(R.id.name);
date_view = (TextView)rowLayout.findViewById(R.id.date);
address_view = (TextView)rowLayout.findViewById(R.id.address);
}
}
public void addLocation(String _name,String _address,Long _date){
//Création d'une nouvelle location avec les données en paramètres
Location new_loc = new Location(_name, _address,_date);
//Ajout de la location à la liste des locations
Locations.add(new_loc);
Collections.sort(Locations);
}
/*Méthodes de la classe mère*/
@Override
public int getCount() {
return Locations.size();
}
@Override
public Object getItem(int position) {
return Locations.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = inflater.inflate(monLayout, parent, false);
ViewHolder holder = (ViewHolder)view.getTag();
if (holder == null)
{
holder = new ViewHolder(view);
view.setTag(holder);
}
Location location = (Location)getItem(position);
holder.name_view.setText(location.name);
holder.address_view.setText(location.address);
Date date=new Date(location.date);
SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
String dateText = df.format(date);
holder.date_view.setText(dateText);
return view;
}
}
答案 0 :(得分:2)
使用自定义Comparator
:
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
或
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
按照你的顺序,你可以这样做:
删除implements
并使用它而不是Collections.sort(Locations)
;
Collections.sort(Locations, new Comparator<Location>() {
@Override
public int compare(final Location object1, final Location object2) {
return object1.name.compareTo(object2.name);
}
}
);