清除后Android Listview重复项目

时间:2014-05-23 10:50:23

标签: android listview android-arrayadapter

我在ListView中遇到重复项目的问题。我读了很多关于它的重复条目没有帮助。找到解决方案真是太棒了。

我无法重现它。我的一位客户告诉我,它有时会发生并给我发送截图,但我不知道为什么。这是我的代码:

    public class NewsFragment extends SherlockFragment implements ActionBar.TabListener
    {

    private ArrayAdapter<NewsEntry> adapter;

    private NewsModel model = new NewsModel();
    private Button mFreistellungButton;
    private boolean mMehrNews;

    private ListView mListView;
    private Button mNewsarchivButton;
    private Fragment mFragment;

    private static boolean mNewsAktualisieren = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.newslistemain, container, false);

        setHasOptionsMenu(true);
        mListView = (ListView) rootView.findViewById(R.id.newsListView);


        adapter = new ArrayAdapter<NewsEntry>(getActivity(), R.layout.custom_list_row, model.getFirstThreeNews());

        mListView.setAdapter(adapter);

        mNewsarchiveButton = (Button) rootView.findViewById(R.id.newsarchiveButton);

        mMoreNews = false;
        mNewsarchiveButton.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                setMoreNews(!isMoreNews());
                updateNews();
            }

        });
}

public void updateNews()
    {
        adapter.clear();
        if (isMoreNews())
        {
            mNewsarchivButton.setText("show 3 News");
            for (int i = 0; i < model.getNews().size(); i++)
            {
                adapter.add(model.getNews().get(i));
            }
        }
        else
        {
            mNewsarchiveButton.setText("Newsarchive");
            for (int i = 0; i < model.getFirstThreeNews().size(); i++)
            {
                adapter.add(model.getFirstThreeNews().get(i));
            }
        }
        adapter.notifyDataSetChanged();
    }

}

1 个答案:

答案 0 :(得分:0)

我认为,这个简单的解决方案是在您想要重新加载它时创建新的适配器:

public void updateNews()
    {
        adapter = new ArrayAdapter<NewsEntry>(getActivity(), R.layout.custom_list_row, new ArrayList());
        if (isMoreNews())
        {
            mNewsarchivButton.setText("show 3 News");
            for (int i = 0; i < model.getNews().size(); i++)
            {
                adapter.add(model.getNews().get(i));
            }
        }
        else
        {
            mNewsarchiveButton.setText("Newsarchive");
            for (int i = 0; i < model.getFirstThreeNews().size(); i++)
            {
                adapter.add(model.getFirstThreeNews().get(i));
            }
        }
this.adapter = adapter;
mListView.setAdapter(adapter);
    }

}

当你无法重现它时,很难找到这个bug。但是如果你要创建新的适配器,你可以肯定,它不可能有旧的元素。

但我建议覆盖BaseAdapter并实现自己的适配器。它可以非常灵活地控制其中的元素并构建自定义ui。