如何更新此viewpager以显示每次搜索的搜索结果

时间:2019-02-09 16:17:59

标签: android android-viewpager

我有一个图书搜索应用程序,可以从服务器获取图书图片。 如何删除以前在viewpager中显示的搜索结果并显示一个新的搜索结果?

我试图将Viewpageradaptor设置为null并制作另一个适配器,但是它不起作用并且应用程序崩溃。

 public class MyViewPagerAdapter extends PagerAdapter {

private Context context;
public String data;

 public MyViewPagerAdapter(Context context,Data data) {
    this.context = context;
 //getting url from main activity
    this.data=data;}

  @Override
  public Object instantiateItem(@NonNull ViewGroup collection, int position) {
    LayoutInflater inflater = LayoutInflater.from(context);
    ViewGroup layout = (ViewGroup)inflater.inflate(R.layout.object_details_image, collection, false);
    ImageView pagerImage = layout.findViewById(R.id.pagerImage);

     //sending image view to another class to get the image from the internet and  show it in my imageview
     //Downloader is a class that I made to download the images and show them in my Imageview


   new Downloader().showImage(pagerImage ,data);


     collection.addView(layout);
      return layout;
   }

   @Override
 public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object view) {
       container.removeView((View) view);
    }

   @Override
   public int getCount() {
   return this.images.size();
   }

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return view == object;
}
   }

在我的主要活动中

    viewPager.setAdapter(new MyViewPagerAdapter(MyApp.getContext(), "image url")

2 个答案:

答案 0 :(得分:0)

您只需要清除this.images数组/列表/ ArrayList并在viewPager适配器上调用adapter.notifyDataSetChanged();

如果this.images是一个ArrayList,则:

adapter.images.clear(); adapter.notifyDataSetChanged();

如果this.images是列表,则:

adapter.images = new ArrayList();
adapter.notifyDataSetChanged();

答案 1 :(得分:0)

每次我想进行其他搜索时,只需创建一个新的适配器对象。

 viewPager.setAdapter(new MyViewPagerAdapter(MyApp.getContext(), "new image url")