我有各种位置名称,它们的经纬度来自服务器端。我使用自定义适配器将它们放在列表视图中。在适配器中,我编写了代码来计算位置与当前位置的距离。每件事都很好,但我想按距离排序。我无法弄清楚如何去做。
我的活动代码是:
List<String> Names = new ArrayList<String>();
List<String> MinLevel = new ArrayList<String>();
Names=db.getId();
MinLevel=db.getMinLevel();
MapAdapter ad=new MapAdapter(this, Names,MinLevel);
lv.setAdapter(ad);
MapAdapter
private final Context context;
private List<String>Name=new ArrayList<String>();
private List<String>Min=new ArrayList<String>();
PharmacyDB db;
public MapAdapter(Context context,List<String>phname,List<String>phmin) {
super();
this.context = context;
this.Name=phname;
this.Min=phmin;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.test_adapter,parent, false);
db=new PharmacyDB(context);
final TextView pharname = (TextView)v.findViewById(R.id.test_ad_name);
final TextView distance = (TextView)v.findViewById(R.id.test_ad_dist);
final TextView rad_min = (TextView)v.findViewById(R.id.test_rad);
final RelativeLayout det=(RelativeLayout)v.findViewById(R.id.details);
pharname.setText(db.getPharmacyName(Name.get(position)));
if(!Min.get(position).equals("null")&&!Min.get(position).equals(null)){
rad_min.setText(Min.get(position));
}
else{
rad_min.setText("NA");
}
if(!db.getLat(Name.get(position)).equals("") && !db.getLat(Name.get(position)).contains("null") && !db.getLat(Name.get(position)).equals(null)&&!db.getLat(Name.get(position)).startsWith("0")){
float dis= distFrom((float)MapTest.mLatitude, (float)MapTest.mLongitude, Float.parseFloat(db.getLat(Name.get(position))), Float.parseFloat(db.getLong(Name.get(position))));
int d=Math.round(dis);
if(d<1000){
distance.setText(String.valueOf(d)+ " Meters");
}
else{
if((d/1000)<50)
distance.setText(String.valueOf(d/1000)+ " Kms");
else
distance.setText("NA");
}
}
else{
distance.setText("NA");
}
return v;
}
@Override
public int getCount(){
// TODO Auto-generated method stub
return Name.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
答案 0 :(得分:0)
我建议您不要计算适配器中的距离
为所有场创建一个简单的bean类,并根据距离实现Comparator or Comparable
和覆盖CompareTo()
方法。
创建该对象的列表,然后调用list.sort();
您将获得排序列表然后将此列表传递给适配器