Saving state of ArrayList of custom objects

前端 未结 2 562
清歌不尽
清歌不尽 2020-12-18 16:33

I have a member variable in my Activity which is an ArrayList. The objects populating this ArrayList are objects I have defined called RatingItem. RatingItem has several m

2条回答
  •  清歌不尽
    2020-12-18 16:46

    One option is to iterate over your ArrayList in onSaveInstanceState and do something like

    RatingItem ri = list.get(i);
    ri.saveState(bundle);
    

    The custom saveState call can then go about saving its individual state to the bundle, like so:

    static final String RATING_KEY = "RATING_KEY";
    int myId;
    int myRating;
    
    void saveState(bundle)
    {
        bundle.putInt(RATING_KEY + "_" + myId, myRating);
    }
    

    The myId member field should be set in RatingItem's constructor, and is used to ensure that all the member fields in an item can be linked back to a particular item at restore time (by reversing the above and using bundle.getInt() with appropriate key+id).

提交回复
热议问题