【问题标题】:How to sort Items in ListView如何对 ListView 中的项目进行排序
【发布时间】:2016-03-08 11:38:30
【问题描述】:

我有一个ListView。每个Item 得到3 个TextViews。对于某些id 中的TextView,如何按字母顺序对Items 进行排序?

我的Adapter代码如下:

public class CustomList extends ArrayAdapter<String>{

private final Activity context;
private final String[] textName;
private final String[] imagePath;
private final String[] textAge;
private final String[] textSex;
public CustomList(Activity context,
                   String[] imagePath, String[] textName, String[] textSex, String[] textAge) {
    super(context, R.layout.listview_row, textName);
    this.context = context;
    this.textName = textName;
    this.imagePath = imagePath;
    this.textAge = textAge;
    this.textSex = textSex;

}
@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.listview_row_mix, null, false);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.NameText);
    TextView txtSex = (TextView) rowView.findViewById(R.id.SexText);
    TextView txtAge = (TextView) rowView.findViewById(R.id.AgeText);

    ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
    txtTitle.setText(textName[position]);
    txtSex.setText(textSex[position]);
    txtAge.setText(textAge[position]);
    String root = Environment.getExternalStorageDirectory().toString();

    File imageFile = new File(root + "/WorkImages/" + imagePath[position]);
    Log.i("Debug", imageFile.toString());
    if(imageFile.exists()){
        Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        imageView.setImageBitmap(myBitmap);
        Log.i("Debug", imageFile.toString());

    }else{
    imageView.setImageResource(R.drawable.profile_icon);}
    return rowView;


 }
}

我认为应该在adapter 代码中进行排序。我查看了类似的问题,但他们使用 1 TextView Items,这意味着他们可以简单地比较和排序 String[] 中的值。如果我在这里做类似的事情,我只会把列表弄乱,因为名称和信息不会对应。

【问题讨论】:

  • Arrays.sort(string_arr);

标签: java android sorting listview


【解决方案1】:

使用 Comparator 接口对列表进行排序,然后将数据设置为适配器。

【讨论】:

    【解决方案2】:

    考虑将与单行相关的所有数据(即姓名、图像路径、性别和年龄)封装在一个类中,然后对这些对象的集合进行排序。

    【讨论】:

      【解决方案3】:

      您可以使用比较器并对列表数据进行排序

        Collections.sort(array, new Comparator<ListData>() {
      
      
                 @Override
                  public int compare(ListData s1, ListData s2) {
                      int returnValue = 0;
                      if (!s1.getName().toLowerCase().startsWith(str.toLowerCase())
                              && !s2.getName().toLowerCase().startsWith(str.toLowerCase())
                              || s1.getName().toLowerCase().startsWith(str.toLowerCase())
                              && s2.getName().toLowerCase().startsWith(str.toLowerCase())) {
                          returnValue = s1.getName().compareToIgnoreCase(s2.getName());
                      } else {
                          if (s1.getName().toLowerCase().startsWith(str.toLowerCase())) {
                              returnValue = -1;
                          } else {
                              returnValue = 1;
                          }
                      }
                      return returnValue;
                  }
              });
      

      【讨论】:

      • 我应该把这个放在适配器还是活动中?
      • 使用新的排序数组再次设置适配器
      【解决方案4】:

      您可以使用直接列表,如下例所示

      List<Type> data_source,order;
      
      Collections.sort(data_source);
      //or
      Collections.sort(data_source, new Sorter(order));
      

      希望对此有所帮助

      【讨论】:

      • 我应该把这个放在 MainActivity 中吗?
      【解决方案5】:

      我建议您将整个数据集保存在单个数据结构中,使用 Comparator 实例对它们进行排序并保留该数据集的副本。

      首先创建具有姓名、年龄、性别、imagePath 的 POJO。这样您就不必单独对每个集合进行排序。

      public class Person {
          public String imagePath;
          public String name;
          public String age;
          public String sex;
      } 
      

      其次,将这些 Person 实例存储在一个集合中。假设我们正在使用 java Array,就像您在适配器示例中所做的那样。

      public class CustomList extends ArrayAdapter<String> {
          private final Person[] people;
          // Other stuff...
      }
      

      现在,让我们添加 Comparator 实例和数据集的副本。

      public class CustomList extends ArrayAdapter<String> {
          private final Person[] people;
          private Comparator<Person> comparator;
          private Person[] peopleSorted;
      
          // Other stuff...
      }
      

      所以,最终的Adapter 实现将类似于

      public class CustomList extends ArrayAdapter<String> {
          private final Person[] people;
          private Comparator<Person> comparator;
          private Person[] peopleSorted;
      
          public CustomList(Activity context, Person[] people) {
              super(context, R.layout.listview_row, textName);
              this.context = context;
              this.people = people;
              this.peopleSorted = Arrays.copyOf(people, people.length);
          }
      
          public void sort(Comparator<Person> comparator) {
              if (comparator == null) {
                  peopleSorted = Arrays.copyOf(people, people.length);
              }
              else {
                  Arrays.sort(peopleSorted, comparator);
              }
      
              // It is up to you to call notifyDataSetChanged implicitly here, or calling it explicitly from somewhere else. 
          }
      
          public void getCount() {
              return peopleSorted.length;
          }
      
          // Other stuff...
      }
      

      请注意,sort API 允许您通过利用多态性来支持 Open/Closed 原则。事情将如何排序不再是 Adapter 的责任。

      【讨论】:

        【解决方案6】:

        我使用this 作为参考。

        而不是Dog(String n, int a),我写了一些东西来满足我的需要。在这种情况下Dog(String a, String b, String c, String d)。然后我添加类似于

        的功能
        public string getDogName(){
        return name;
        }
        

        喜欢

        public string getDogSex(){
        return sex;
        }
        

        然后在活动中我使用这个:

        list.add(new Dog(a[pos], b[pos], c[pos], d[pos]));
        

        a, b, c, dString[]

        排序本身是用

        Collections.sort(list);
        

        如果您想更改确切排序的内容,请更改此字符串。

        return (this.name).compareTo(d.name);
        

        你写了多种可能性,比如return (this.age).compareTo(d.age);, 用if 声明包围它们。

        if(counter == 1){
        return (this.name).compareTo(d.name);
        }
        

        计数器是public static int;。该值通过button.onClickListener 进行更改 - 它允许动态排序。

        如果这看起来令人困惑,请尝试仅使用链接中提供的代码,然后再尝试修改它。

        【讨论】:

          【解决方案7】:

          这默认按升序对数据进行排序。

          Collections.sort(galaxiesList);
          

          然后我们可以将其反转为降序,这与升序相反:

          Collections.reverse(galaxiesList)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-01-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-20
            • 2012-03-10
            相关资源
            最近更新 更多