android - 使用 Spinner Android 对自定义 ListView 项目进行排序

标签 android sorting listview spinner android-arrayadapter

我尝试使用微调器选择排序样式后按字母顺序和数字顺序对 ListView 中的项目进行排序。本质上,每当用户选择微调项目时, ListView 都会根据他们选择的选项进行排序。由于这是一个带有自定义适配器的自定义 ListView ,我在寻找一种实际正确排序的方法时遇到了一些问题。如果有人能给我一些关于如何解决这个问题的建议,我将不胜感激。 下面是我现在处理显示 ListView 的主类:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_repetition_progress);

    /**
     * The database used to pull all exercises for this workout routine
     */
    DatabaseHandler db = new DatabaseHandler(this);
    SQLiteDatabase database = db.getReadableDatabase();

    context = this;


    /**
     * Get all exercises from Triceps and Chest workout and put in arraylist
     */
    ListView workoutExerciseList = (ListView)findViewById(R.id.listView7);
    final List<String> arrayRepetitionProgress = new ArrayList<String>();
    exListAdapter = new ArrayAdapter<String>(this,
           android.R.layout.simple_spinner_item, arrayRepetitionProgress);
    workoutExerciseList.setAdapter(exListAdapter);

    //Holds all the available exercises
    final List<WorkoutTracker> exerciseList = db.getRepProgress(context, database);

    /**
     * Populates the listView with each exercise for this workout routine. This includes the
     * each exercise name, the distance, the time of the workout, and any
     * comments included.
     */
    repProgressList = new ArrayList<RepetitionProgress.ListViewItem>();
    for(int i = 0; i<exerciseList.size(); i++) {
        final int j = i;
        repProgressList.add(new ListViewItem()
        {{
                REPETITIONS = exerciseList.get(j).getReps();
                WEIGHT = exerciseList.get(j).getWeight();
                COMMENT = exerciseList.get(j).getComment();
                EXERCISE_NAME = exerciseList.get(j).getExerciseName();
                DATE = exerciseList.get(j).getDate();
            }});


    }
    final RepetitionProgressAdapter adapter = new RepetitionProgressAdapter(this, repProgressList);
    workoutExerciseList.setAdapter(adapter);


    //Spinner used to select sorting method
    SortOptions = (Spinner)findViewById(R.id.sortOption);
    SortOptions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            //If the Sort by exercise name option is chosen
            if(SortOptions.getSelectedItem().toString().equals("Sort by exercise name")) {
                Toast.makeText(context.getApplicationContext(), "Sort by exercise name", Toast.LENGTH_LONG).show();
                exListAdapter.sort(new Comparator<String>() {
                    @Override
                    public int compare(String lhs, String rhs) {
                        return lhs.compareTo(rhs);
                    }
                });
                //Refresh the listview
                adapter.notifyDataSetChanged();
                exListAdapter.notifyDataSetChanged();
            }


            //If the Sort by date option is chosen
            if(SortOptions.getSelectedItem().toString().equals("Sort by date")) {
                Toast.makeText(context.getApplicationContext(), "Sort by date", Toast.LENGTH_LONG).show();
            }

            //If the Sort by number of repetitions option is chosen
            if(SortOptions.getSelectedItem().toString().equals("Sort by number of repetitions")) {
                Toast.makeText(context.getApplicationContext(), "Sort by number of repetitions", Toast.LENGTH_LONG).show();
            }

            //If the Sort by weight option is chosen
            if(SortOptions.getSelectedItem().toString().equals("Sort by weight")) {
                Toast.makeText(context.getApplicationContext(), "Sort by weight", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    Back = (Button)findViewById(R.id.back);
    Back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

下面是我的自定义适配器类的部分,用于设置每个 ListView 项中看到的属性:

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    ListViewItem item = items.get(position);
    View vi=convertView;

    if(convertView==null)
        vi = inflater.inflate(R.layout.rep_progress_view, null);


    TextView exerciseName = (TextView)vi.findViewById(R.id.FullProgress);
    TextView exerciseComment = (TextView)vi.findViewById(R.id.Comment);


    exerciseName.setText(item.EXERCISE_NAME + "    Date: " + item.DATE + "    Reps: " + item.REPETITIONS + "    Weight: " +item.WEIGHT + " Pounds    ");
    exerciseComment.setText(item.COMMENT);

    return vi;
}

最佳答案

下面是示例代码,您可以查看并在您的代码中实现相同的代码..

public static void main(String[] args) {

    List<Item> items = new ArrayList<>();
    // constructor Item(name, Id, weight)
    items.add(new Item("Nelson", 1, 10.3));
    items.add(new Item("Fisk", 2, 12.03));
    items.add(new Item("Speedy", 3, 19.3));
    items.add(new Item("Donna", 4, 12.3));
    items.add(new Item("Matt", 5, 16.3));
    items.add(new Item("Oliver", 6, 1.3));
    items.add(new Item("Deadstroke", 5, 1.3));

    Collections.sort(items, new MyComparator(MyComparator.NAME));

    for (Item item : items) {
        System.out.println("Items   " + item.getName() + " \t" + item.getWeight());
    }
}

static class MyComparator implements Comparator<Item> {
    static final int NAME = 0, WEIGHT = 1, DATE = 2;
    int type;

    public MyComparator(int type) {
        this.type = type;
    }

    @Override
    public int compare(Item o1, Item o2) {

        if (type == NAME) {
            return o1.getName().compareTo(o2.getName());
        } else if (type == WEIGHT) {
            if (o1.getWeight() > o2.getWeight())
                return 1;
            else if (o1.getWeight() == o2.getWeight())
                return 0;
            else
                return -1;
        } else if (type == DATE) {
            // now convert your date object/string to milliseconds and apply
            // number logic (above)
        }
        return 0;
    }
}

以及如何在 Spinner 中调用,

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selectedItem = parent.getItemAtPosition(position).toString();

    if (selectedItem.equals("Sort by exercise name")) {
        // Collections.sort(items, new MyComparator(MyComparator.NAME));
        //replace with your code/array list
    } else if (selectedItem.equals("Sort by date")) {
        // Collections.sort(items, new MyComparator(MyComparator.DATE));
    } else if (selectedItem.equals("Sort by number of repetitions")) {
        // Collections.sort(items, new MyComparator(MyComparator.REPTS));
    } else if (selectedItem.equals("Sort by weight")) {
        // Collections.sort(items, new MyComparator(MyComparator.WEIGHT));
    }
    adapter.notifyDataSetChanged();
    exListAdapter.notifyDataSetChanged();
}

关于android - 使用 Spinner Android 对自定义 ListView 项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347428/

相关文章:

android 在 textview _EDIT 末尾追加 '…'

android - 如果未调用 setcontentview(),为什么 findViewById() 返回 null?

python - 使用合并排序合并和排序列表

c - 排序算法的c实现

可编辑所有记录的 ASP.NET Gridview

android - 如何将小部件放置在 ListView 的上方和下方?

android - 如何使用 aSmack 获取多用户聊天室的 DiscussionHistory?

android.database.sqlite.SQLiteException : no such column : id (code 1) while compiling : s

android - 使用离线同步设计 Android 应用程序。我应该使用 SyncAdapter 吗?

javascript - 在对象数组中,返回任何值与特定字符串匹配的对象