C0deAttack C0deAttack - 5 months ago 120
Android Question

ViewPager PagerAdapter not updating the View

I'm using the ViewPager from the compatibility library. I have succussfully got it displaying several views which I can page through.

However, I'm having a hard time figuring out how to update the ViewPager with a new set of Views.

I've tried all sorts of things like calling

even creating a brand new adapter each time I want to use a new List of data.

Nothing has helped, the textviews remain unchanged from the original data.

Thanks for your time.

I made a little test project and I've almost been able to update the views. I'll paste the class below.

What doesn't appear to update however is the 2nd view, the 'B' remains, it should display 'Y' after pressing the update button.

public class ViewPagerBugActivity extends Activity {

private ViewPager myViewPager;
private List<String> data;

public void onCreate(Bundle savedInstanceState) {

data = new ArrayList<String>();

myViewPager = (ViewPager) findViewById(R.id.my_view_pager);
myViewPager.setAdapter(new MyViewPagerAdapter(this, data));

Button updateButton = (Button) findViewById(R.id.update_button);
updateButton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

private void updateViewPager() {

private class MyViewPagerAdapter extends PagerAdapter {

private List<String> data;
private Context ctx;

public MyViewPagerAdapter(Context ctx, List<String> data) {
this.ctx = ctx;
this.data = data;

public int getCount() {
return data.size();

public Object instantiateItem(View collection, int position) {
TextView view = new TextView(ctx);
return view;

public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);

public boolean isViewFromObject(View view, Object object) {
return view == object;

public Parcelable saveState() {
return null;

public void restoreState(Parcelable arg0, ClassLoader arg1) {

public void startUpdate(View arg0) {

public void finishUpdate(View arg0) {


There are several ways to achieve this.

The first option is easier, but bit more inefficient.

Override getItemPosition in your PagerAdapter like this:

public int getItemPosition(Object object) {
    return POSITION_NONE;

This way, when you call notifyDataSetChanged(), the view pager will remove all views and reload them all. As so the reload effect is obtained.

The second option, suggested by Alvaro Luis Bustamante (previously alvarolb), is to setTag() method in instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update.

The second approach is very flexible and high performant. Kudos to alvarolb for the original research.