ListView按字母顺序排列,没有Comparable

时间:2016-04-29 19:04:54

标签: java android listview android-studio alphabetical

我试图通过WORDS列的值按字母顺序放置此ListView。我已经阅读过关于这个主题的答案,但是还没有找到任何解决方案。我是否必须使用Comparable / Comparator?

private ArrayList<HashMap<String, Object>> wordList;
private static final String WORD = "word";
private static final String DEFINITION = "definition";
private static final String NOTES = "notes";
private SimpleAdapter adapter;

ListView listView = (ListView) findViewById(R.id.listView);
final ListView listView2 = (ListView) findViewById(R.id.listView2);
wordList = new ArrayList<>();
HashMap<String, Object> hm;

for (int i = word_counter - 1; i >= 0; i--) {
    hm = new HashMap<>();
            hm.put(WORD, words[i]);
            hm.put(DEFINITION, definitions[i]);
            hm.put(NOTES, notes[i]);
            wordList.add(hm);
    } 

adapter = new SimpleAdapter(this, wordList,
    R.layout.list_item, new String[]{WORD, DEFINITION, NOTES},
    new int[]{R.id.text1, R.id.text2, R.id.text3});

1 个答案:

答案 0 :(得分:1)

对于自动排序数据,请使用 TreeSet 。 TreeSet是一个集合,无论您在其中输入数据的顺序如何,您在其中输入的数据都将被排序。

    TreeSet ts=new TreeSet();
    for (int i=0;i<words.length;i++)
    {
        ts.add(words[i]+"-|-"+definitions[i]+"-|-"+notes[i]);
    }
    Iterator<String> itr=ts.iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());
    }

输出将按升序排列。从这里开始,只需使用&#34; - | - &#34;分割从TreeSet获得的字符串。作为split()的参数。并根据需要使用每个元素。

相关问题