[英]How do I sort my ListAdapter by Difficulty - Easy, Medium and then Hard?
I've got this code below in order to sort my ListView items depending on the name of the item: 我有以下代码,以便根据项目的名称对ListView项目进行排序:
case R.id.menu_order_name:
adapter.sort(new Comparator<Shop>() {
@Override
public int compare(Shop arg0, Shop arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
return true;
I have a slight issue in the fact that I also want to have an ActionBar menu option to sort by the difficulty too: the difficulties being easy, medium and hard. 我有一个小问题,我也希望有一个ActionBar菜单选项来按难度排序:困难是简单,中等和困难。 The problem is, if I use the same sort method, it sorts them by easy, hard, medium...as they are in the alphabet. 问题是,如果我使用相同的排序方法,它会通过简单,坚硬,中等的方式对它们进行排序......因为它们在字母表中。 Can anybody help me in setting it so that it compares them to the actual difficulty level, from easy to hard and how would I specify this order? 任何人都可以帮我设置它,以便将它们与实际难度级别进行比较,从易到难以及如何指定此顺序?
Thanks in advance! 提前致谢! All help will be greatly appreciated as I have no clue. 所有的帮助将不胜感激,因为我不知道。
You want your comparator to be something like; 你希望你的比较器是这样的;
new Comparator<Shop>() {
@Override
public int compare(Shop arg0, Shop arg1) {
return nameToInt(arg0.getName())-nameToInt(arg1.getName());
}
private static int nameToInt(String name)
{
if(name.equals("easy"))
return 0;
if(name.equals("medium"))
return 1;
if(name.equals("hard"))
return 2;
return 3;
}
}
Using enums in your object to identify easy med hard could make this much cleaner. 在你的对象中使用枚举来识别容易的med可以使这更加清洁。
I finally fixed the sorting by difficulty, thanks to the help from @Robadob giving me ideas. 由于@Robadob的帮助给了我一些想法,我终于通过难度修复了排序。
case R.id.menu_order_difficulty:
adapter.sort(new Comparator<Shop>() {
@Override
public int compare(Recipe arg0, Recipe arg1) {
return (difficulty(arg0.getDifficulty())-difficulty(arg1.getDifficulty()));
}
private int difficulty(String name)
{
if(name.equals("Easy"))
return 0;
else if (name.equals("Medium"))
return 1;
else if(name.equals("Hard"))
return 2;
return 0;
}
});
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
return true;
I thought I'd post my fully completed answer in case this helps anyone in the future. 我想我会发布完整的答案,以防将来有人帮忙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.