如何自定义适配器以限制要显示的项目

时间:2018-08-30 22:46:18

标签: java android

我的应用正在使用适配器显示对象,我想限制它,以便仅显示前10个项目

这是我正在使用的代码

public void onResponse(TopScoreObject[] response) {
            try {
                if(response != null){
                    List<TopScoreObject> mList = arrayToListObject(response);
                    Collections.sort(mList, new Comparator<TopScoreObject>() {
                        @Override
                        public int compare(TopScoreObject topScoreObject, TopScoreObject t1) {
                            return Integer.parseInt(topScoreObject.getScores()) - Integer.parseInt(t1.getScores());
                        }
                    });
                    Collections.reverse(mList);
                    mAdapter = new LadderBoardAdapter(mList);
                    mRecyclerView.setAdapter(mAdapter);

默认情况下,它显示列表中的所有项目,但我只想显示其中的前10个。

2 个答案:

答案 0 :(得分:0)

为什么不遍历列表并删除大于索引9的元素?

while(mList.size() > 10) {
     mList.remove(10);
}

答案 1 :(得分:0)

    public void onResponse(TopScoreObject[] response) {
        try {
            if(response != null){
                ArrayList<TopScoreObject> mList = arrayToListObject(response);
                if(mList.size() > 10)
                    mList.subList(10, mList.size()).clear();

                Collections.sort(mList, new Comparator<TopScoreObject>() {
                    @Override
                    public int compare(TopScoreObject topScoreObject, TopScoreObject t1) {
                        return Integer.parseInt(topScoreObject.getScores()) - Integer.parseInt(t1.getScores());
                    }
                });
                Collections.reverse(mList);
                mAdapter = new LadderBoardAdapter(mList);
                mRecyclerView.setAdapter(mAdapter);