BookListing项目。每本书的搜索都与之前的结果重叠。你如何清除ListView?

时间:2017-10-12 16:57:45

标签: android listview fragment onclicklistener loader

这是我的onClick信息:

        Button searchButton = (Button) findViewById(R.id.search_button);
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                BookListFragment bookListFragment = new BookListFragment();

                getSupportFragmentManager().beginTransaction()
                        .add(R.id.book_list_frame, bookListFragment).commit();

            }

    });

BookListFragment w / BookLoader:

    @Override
public Loader<List<BookListing>> onCreateLoader(int i, Bundle args) {

    return new BookLoader(this, GOOGLE_BOOKS_URL + searchedBook);
}


@Override
public void onLoadFinished(Loader<List<BookListing>> loader, List<BookListing> bookListings) {
    mAdapter.clear();


    if(bookListings != null && !bookListings.isEmpty()) {
        mAdapter.addAll(bookListings);
    }

}

@Override
public void onLoaderReset(Loader<List<BookListing>> loader) {
    mAdapter.clear();

}

我能够获得搜索结果。但是当再次搜索时,之前的结果并不清楚。它们只是不断重叠。

First Search Screenshot Second Search Screenshot

5 个答案:

答案 0 :(得分:2)

 @Override
 public Loader<List<BookListing>> onCreateLoader(int i, Bundle args) {

 return new BookLoader(this, GOOGLE_BOOKS_URL + searchedBook);
 }


@Override
public void onLoadFinished(Loader<List<BookListing>> loader, 
    List<BookListing> bookListings) {
         mAdapter.clear();


if(bookListings != null && !bookListings.isEmpty()) {
    mAdapter.replace(bookListings);
    }

}
@Override
public void onLoaderReset(Loader<List<BookListing>> loader) {
mAdapter.clear();
 }

答案 1 :(得分:0)

添加BookListFragment时,请使用replace()代替add()

getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.book_list_frame, bookListFragment)
    .commit();

希望有所帮助

答案 2 :(得分:0)

您必须使用replace()代替add()

 getSupportFragmentManager().beginTransaction()
                            .replace(R.id.book_list_frame, bookListFragment).commit();

应该这样做

答案 3 :(得分:0)

这是一个解决方案。首先获取父视图(ListView),删除所有子视图(行)。

public void removeView(View v) {
    if(v.getParent() != null) {
        ((ViewGroup) v.getParent()).removeView(v);
    }
}

为ListView中的每一行调用removeView(v)。在这种情况下,所有行共享一个父级,因此尝试使该父级为实例字段,然后上面的方法为:

ListView listView;

. . .

public static void removeView(View v) {
    listView.removeView(v);
}

您还可以通过以下方式删除所有行:

listView.removeAllViews();

希望这有帮助!

答案 4 :(得分:0)

difference between fragmentTransaction.add and fragmentTransaction.replace 再加上CamiloCons的答案,每当你调用add()时,你就会“添加”一层新的片段。