NotifyDataSetChanged未刷新ViewPager

时间:2015-07-31 13:41:32

标签: android android-viewpager notifydatasetchanged

我正在研究ViewPager Concept。在ViewPager项目单元格中包含两个项目,如ImageView和TextView。

最初,我将下载Blur Image并在ViewPager单元格中显示。完成后,我将分别下载HighResolution图像并在ViewPager单元格中显示。

例如,如果我将ViewPager中的第一个项目视为模糊图像,并且在背景中它正在下载HighResolution图像,那么它必须刷新ViewPager并在相应的视图单元格中显示HighResolution图像。

在滑动两个项目然后返回第一个项目后,该时间显示高分辨率图像。

所以我的问题是没有向左或向右滑动,如果当前视图中发生任何更改,我需要刷新当前视图。

ViewPager活动类:

public class ViewPagerActivity extends Activity {
ViewPager pager;
String[] _blurImageURL;

PagerAdapter _pagerAdapter;
Context _context;

ViewPagerModel vpModel = new ViewPagerModel();

ArrayList<String> lstQueue=new ArrayList<String>();
Handler _handler=new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_pager);
    pager = (ViewPager) findViewById(R.id.pagerView);
    _context = this;

    _blurImageURL = new String[]{

            "http://cdn.connollyphoto.nyc/wp-content/uploads/2014/06/cp_seanbell_portrait_002-800x1200.jpg",
            "http://static.wixstatic.com/media/e6f301_7d57a9c0ebdf4d438f88633637aaed77.jpg_srz_930_1395_85_22_0.50_1.20_0.00_jpg_srz",
            "http://a4.format-assets.com/image/private/s--TmkImGBO--/c_limit,g_center,h_1200,w_65535/a_auto,fl_keep_iptc.progressive,q_95/31336-7293530-portrait-1_jpg2.jpg",
            "http://daviddodgephotography.com/wp-content/uploads/2015/03/Donna_12.jpg",
            "http://a3.format-assets.com/image/private/s--W9Flct-g--/c_limit,g_center,h_1200,w_65535/a_auto,fl_keep_iptc.progressive,q_95/173355-8951465-Marvin_Portraits-005.jpg",
            "http://www.leifnorman.net/wp-content/uploads/2014/10/IMG_6070.jpg",
            "https://dwaynefoong.files.wordpress.com/2012/05/amin-fashion-portrait-dwayne-foong-photography.jpg",
            "https://m1.behance.net/rendition/modules/117495331/hd/ce856c4a1fb4c09a5ecec05839f6ddc4.jpg",
            "http://www.pcimagenetwork.com/perks/Perks%202013.jpg",
    };


    _pagerAdapter = new ViewPagerAdapter(_context, vpModel, this);
    pager.setAdapter(_pagerAdapter);

    // Calling Volley Library to Download the Image for each URLi

    for (int i = 0; i < _blurImageURL.length; i++) {
        String fileName = String.valueOf(i);
        fileName=fileName+"_blurImg";

        DownloadImages(_blurImageURL[i], fileName, true);
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.view_pager, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void updateView() {
    _pagerAdapter.notifyDataSetChanged();
}
 public void DownloadQueue(String url_in,String fileName_in)
 {
     if(lstQueue.contains(fileName_in))
     {
         Log.i("Duplicate_Request=",fileName_in);
     }
     else{
         lstQueue.add(fileName_in);
         DownloadImages(url_in,fileName_in,false);
     }

 }

void DownloadImages(String imageURL_in, final String fileName_in, final boolean isBlur_in) {
    ImageRequest imageRequest = new ImageRequest(imageURL_in,
            new Response.Listener<Bitmap>() {

                @Override
                public void onResponse(final Bitmap response) {
                    try {
                        Log.v("Response_Received =",fileName_in);
                        // Saved in SD Card and getting the Path
                        String imagePath = SavedInSDCard(response,fileName_in);

                        //updating the Model
                        if (isBlur_in) {
                            vpModel.blurImgLocalPath.add(imagePath);

                        } else {
                            vpModel.highResolutionImgLocalPath.add(imagePath);
                        }

                          //updating the View
                        _handler.post(new Runnable() {
                            @Override
                            public void run () {
                                updateView();
                            }
                        });  


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 0, 0, null, null);
    ApplicationController.getInstance().addToRequestQueue(imageRequest);

}

public String SavedInSDCard(Bitmap bitmap, String fileName_in) {

    File dir = new File(ApplicationController.getAppContext()
            .getExternalFilesDir("ViewPager_POC") + "/Cache");
    // Create the storage directory if it does not exist
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(dir, fileName_in);
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    String imgPath = dir + "/" + fileName_in;
    return imgPath;
}


}

ViewPager适配器类:

public class ViewPagerAdapter extends PagerAdapter {
Context _context;
LayoutInflater inflater;
ViewPagerActivity _vpActivity;

String[] _highResolutionURL = new String[]{
        "http://www.monportraitpro.fr/wp-content/uploads/2014/08/Philippe-Vasilescu.jpg",
        "http://www.markhicksphotography.com/wp-content/uploads/2012/01/MHP2012_01_04_MHP_DSC0003.jpg",
        "http://www.andrew-mason.com/wp-content/uploads/2013/05/portrait-1-3.jpg",
        "http://shutterfinger.typepad.com/.a/6a00e551a6244a8833019affd0eb14970d-pi",
        "http://www.antonioolmos.com/data/photos/90_1childs_livebooks.jpg",
        "http://www.dvdsreleasedates.com/pictures/800/12000/Zachary-Quinto.jpg",
        "http://www.glnphotography.com/wp-content/uploads/2013/09/IMG_1347.jpg",
        "http://www.dvdsreleasedates.com/pictures/800/12000/Paul-Walker.jpg",
        "http://www.antonioolmos.com/data/photos/89_1blairbooks.jpg",
};

ArrayList<String> _blurImgPath;
ArrayList<String> _highResolutionImgPath;

public ViewPagerAdapter(Context context_in, ViewPagerModel vpModel_in, ViewPagerActivity activity_in) {
    _context = context_in;
    _blurImgPath = vpModel_in.blurImgLocalPath;
    _highResolutionImgPath = vpModel_in.highResolutionImgLocalPath;
    _vpActivity = activity_in;

}

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

@Override
public void destroyItem(View container, int position, Object object) {
    // TODO Auto-generated method stub
    ((ViewPager) container).removeView((View) object);
}

@Override
public Object instantiateItem(ViewGroup container, final int position) {

    // Declare Variables
    TextView txtCounter;
    final ImageView imgView;

    inflater = (LayoutInflater) _context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.view_pager_item, container,
            false);

    txtCounter = (TextView) itemView.findViewById(R.id.counter);


    imgView = (ImageView) itemView.findViewById(R.id.images);

    //Setting the values for Image and textview
    txtCounter.setText("" + (position + 1));

    //Setting the Image
    if (position < _highResolutionImgPath.size()) {
        //Setting Hi-ResImage
        Log.v("HighRes_ImgPath=", "Get Image from Model" );
        imgView.setImageBitmap(BitmapFactory.decodeFile(_highResolutionImgPath.get(position)));
    } else {
        // Generating the request for HighResolution Image
        String fileName = String.valueOf(position + 10);
        fileName = fileName + "_clearImg";

        Log.v("HighRes_ImgPath=", "Sending Request to Queue=" + fileName);
        _vpActivity.DownloadQueue(_highResolutionURL[position], fileName);
        //Setting the BlurImage
        imgView.setImageBitmap(BitmapFactory.decodeFile(_blurImgPath.get(position)));

    }


    // Add viewpager_item.xml to ViewPager
    ((ViewPager) container).addView(itemView);

    return itemView;
}

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

}

ViewPager模型:

public class ViewPagerModel {

ArrayList<String> blurImgLocalPath=new ArrayList<String>();
ArrayList<String> highResolutionImgLocalPath=new ArrayList<String>();
}

activity_view_pager.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.poc_viewpager.ViewPagerActivity" >

 <android.support.v4.view.ViewPager
    android:id="@+id/pagerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
      />

/>

view_pager_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
    android:id="@+id/images"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:layout_alignParentLeft="true" />

<TextView
    android:id="@+id/counter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="43dp" />


</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

在这种情况下,我会使用Picasso

例如:

Picasso.with(getActivity())
                        .load(URL_THUMBNAIL) // thumbnail url goes here

                        .into(IMAGEVIEW, new Callback() { // Your image view

                            // On success start loading the full resolution image
                            @Override
                            public void onSuccess() {       

                                Picasso.with(getActivity())

                                        .load(FULL_RESOLUTION_URL) // image url goes here
                                        .into(IMAGEVIEW);
                            }

                            @Override
                            public void onError() {
                                // Manage downloading errors here
                            }
                        });

答案 1 :(得分:0)

在后台线程上调用updateView()notifyDataSetChanged()无法在后台线程上运行。在UI线程上调用notifyDataSetChanged()方法,它应该可以解决您的问题

相关问题