【问题标题】:Add String to adapter将字符串添加到适配器
【发布时间】:2011-11-22 09:25:43
【问题描述】:

我有一个适配器,我想向它添加一个字符串,但是当我运行此代码时,它只在songstoadd 变量中添加最后一个字符串......这是一个自定义适配器,它在必要的地方但在数组中添加分隔符适配器我想要一个名称中第一个字母相同的所有字符串....

SeparatedListAdapter adapter = new SeparatedListAdapter(this);
     ArrayList<String> songstoadd = new ArrayList<String>();

              Collections.sort(songtitle);
              int m = 0;
              while( m <songtitle.size()-1){
                  if(songtitle.get(m).substring(0, 1) == songtitle.get(m+1).substring(0, 1)){
                      m++;
                  }else{
                   songstoadd.clear();
                   songstoadd.add(songtitle.get(m));

                adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

              m++;
                  }



      }
              setListAdapter(adapter);

        }

【问题讨论】:

  • 我认为您需要将 Arraylist 转换为 String[] 数组
  • 看看我编辑的答案。访问链接..

标签: android arrays list adapter


【解决方案1】:

试试这个,然后告诉我会发生什么..

songstoadd.clear();
 while( m <songtitle.size()-1){
                  if(songtitle.get(m).substring(0, 1).equals( songtitle.get(m+1).substring(0, 1))){
                      m++;
                  }else{

                songstoadd.add(songtitle.get(m));
                adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

              m++;
                  }

更多信息请看

Android: how to use SectionIndexer

Using AlphabetIndexer for fastscrolling ListView

Create easy alphabetical scrolling in ListView?

【讨论】:

  • 它仍然将每首歌曲的标题添加到每个部分
【解决方案2】:

尝试如下更改您的 while 并尝试..

while(m <songtitle.size()-1){
     if(songtitle.get(m).substring(0, 1) == songtitle.get(m+1).substring(0, 1)){
         songstoadd.add(songtitle.get(m));
         m++;
     }else{

         songstoadd.add(songtitle.get(m));

         adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

         songstoadd.clear();

         m++;
    }
}

【讨论】:

  • 这只会添加 Section Header 而不是 songtitle 数组中的任何内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多