How to update the content of view pager once it is initialized?

人盡茶涼 提交于 2020-02-08 07:20:51

问题


I have a view pager in the MainActivity, this view pager contains two tabs RecentFeed and SavedFeed both uses the same FeedFragment as both has same layout

Now I want to update the contents of these fragments when a new gcm message is recieved or there occurs a change in my database

here is what have done so far :

I created a changelistening interface as follows-

public interface OnDatabaseChangeListener {

void onChange();
}

Then used this in helper class to notify changes as follows

private OnDatabaseChangeListener databaseChangeListener;
public void setDatabaseChangeListener(OnDatabaseChangeListener databaseChangeListener){
    this.databaseChangeListener = databaseChangeListener;
}


public void addNewAlertToDB(Alert alert) {
        .
        .     
    databaseChangeListener.onChange();
    Log.d(TAG, "Added new alert " + title);
}

then Inside my GCMListenerService I do this

            DatabaseHelper.getInstance(this).addNewAlertToDB(alert);
            DatabaseHelper.getInstance(this)
                    .setDatabaseChangeListener(new OnDatabaseChangeListener() {
                @Override
                public void onChange() {
                       //what should I do here to update viewpager content in MAinActivity
                }
            });

Similarly inside My RecentFeed tab I click a feed to save ...so that it is moved to SavedFeed tab...

void onSaveClicked(View view, int pos) {
    DatabaseHelper.getInstance(context)
            .saveAlert(alerts.get(pos));
    DatabaseHelper.getInstance(context)
            .setDatabaseChangeListener(new OnDatabaseChangeListener() {
                @Override
                public void onChange() {
                     //what should I do here to update viewpager content in MAinActivity
                }
            });
    removeItem(pos);
    addItem(0);
    Snackbar.make(view, "Item Saved", Snackbar.LENGTH_LONG)
            .setAction("UNDO", null).show();
    view.setEnabled(false);
}

But to my surprise SavedFeed is still empty.... Now If I close the app and restart ...the savedfeed tab is having content. So I figured that content is being saved but not update on viewpager adapter of saved feed.

So what I want to know is how to update content instantly in RecentFeed when it recieves a gcm-message and how to update savefeed when a feed is saved from recentfeed.


回答1:


Make sure that you are doing the following in your feed listview's adapter:

 adapter.notifydatasetchanged()

As for viewpager you can do this just in case (though the default is 1 or 2):

 viewpager.setOffscreenpagelimit

Besides of all, make sure that these functions are executed on the UI thread.



来源:https://stackoverflow.com/questions/32996883/how-to-update-the-content-of-view-pager-once-it-is-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!