I did it like this: first create an abstract softCache class:
public abstract class SoftCache<T> { private Stack<Reference<T>> mRecyclingStack; final Class<T> classType; public SoftCache(Class<T> typeParameterClass) { this.classType = typeParameterClass; mRecyclingStack = new Stack<Reference<T>>(); } public abstract T runWhenCacheEmpty(); public T get() { T itemCached = null; if (mRecyclingStack.isEmpty()) { itemCached = runWhenCacheEmpty(); } else { SoftReference<T> softRef = (SoftReference<T>) mRecyclingStack .pop(); Object obj = softRef.get(); if (obj == null) { itemCached = runWhenCacheEmpty(); } else { itemCached = (classType.cast(softRef.get())); } } return itemCached; }
now inherits from SoftCache, so we can implement the runWhenCacheEmpty method:
public class ViewCache extends SoftCache<View>{ public ViewCache(Class<View> typeParameterClass) { super(typeParameterClass); } @Override public View runWhenCacheEmpty() { return mFragment.getActivity().getLayoutInflater() .inflate(R.layout.mypagelayout, null); } }
then in your constructor create an instance of this type if you want it to be for the View class (for example, it can work for any type of class):
SoftCache<View> myViewCache = new ViewCache(View.class);
Now in destroyItem save the view in cache:
@Override public void destroyItem(final ViewGroup container, final int position, final Object object) { final View v = (View) object; if(v.getId() == R.id.mypagelayout) myViewCache.put(v);
now the instantiateItem method to use it just like this:
@Override public Object instantiateItem(final ViewGroup container, final int position) { View MyPageView=myViewCache.get(); }
update: if you want to use the cache for different layouts or don't want to expand it, I came up with a solution in which you can use the same cache for several layouts, where you could get the layout that you entered using the layout ID
public class SoftViewCache { private HashMap<Integer,ArrayList<SoftReference<View>>> multiMap; public SoftViewCache() { multiMap= new HashMap<Integer, ArrayList<SoftReference<View>>>(); } public View get(int id) { View itemCached = null; if (!multiMap.containsKey(id)) { return null; } else { SoftReference<View> softRef =multiMap.get(id).get(0); Object obj = softRef.get(); if (null == obj) { return null; } else { itemCached = (softRef.get()); } } return itemCached; } public void put(View item) { SoftReference<View> ref = new SoftReference<View>(item); int key = item.getId(); if (multiMap.containsKey(key)) { multiMap.get(key).add(ref); } else { ArrayList<SoftReference<View>> list = new ArrayList<SoftReference<View>>(); list.add(ref); multiMap.put(key, list); } } }
j2emanue Aug 6 '14 at 19:59 2014-08-06 19:59
source share