【发布时间】:2015-04-04 07:57:50
【问题描述】:
我正在尝试使用 Comparable java 接口及其方法 Compareto() 按字母顺序对添加到 ListView 的元素进行排序。
这是我实现的适配器的代码:我尝试在 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;
}
}
【问题讨论】:
-
有什么问题吗?有什么问题?
-
其实我没有得到我想要的结果,activity打开时显示ListView,但是元素没有按字母顺序排序。
标签: java android listview android-studio