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

BookListing project. Each book search overlaps previous results. How do you clear ListView?

这是我的点击信息:

        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

添加 BookListFragment 时,使用 replace() 而不是 add()

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

希望对您有所帮助

您必须使用 replace() 而不是 add()

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

应该这样做

这是一种解决方案。通过首先获取父视图 (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();

希望对您有所帮助!

difference between fragmentTransaction.add and fragmentTransaction.replace 只需进一步添加到 CamiloCons 答案中,每次调用 add() 时,您都会 "adding" 在顶部添加一层新的片段。

 @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();
 }