我試圖解決創建SerializableSparseArray
延長SparseArray
使其能夠把SparseArray
成束通過Bundle.putSerializable
電話。
但我發現我無法從包中保存的對象onRestoreInstanceState
。深入研究這個問題,我發現savedInstanceState.getSerializable(KEY_TO_STRING_SPARSE_ARRAY) == null
。
然後,試圖檢查savedInstanceState.get(KEY_TO_STRING_SPARSE_ARRAY)
並出乎意料地得到了SparseArray<String>
而不是SerializableSparseArray<String>
。最後,我使用savedInstanceState.getSparseParcelableArray(KEY_TO_STRING_SPARSE_ARRAY)
從捆綁中獲得SparseArray
。
然後,使用java反射保存SparseArray<String>
直接捆綁而不用與Serializable
或Parcelable
接口進行擴展。這有點髒,但我認爲你可以讓自己的實用功能隱藏下面的細節實現。
try {
// FIXME WTF
Method m = Bundle.class.getMethod("putSparseParcelableArray", String.class, SparseArray.class);
m.invoke(savedInstanceState, KEY_TO_STRING_SPARSE_ARRAY, mSparseStringArray);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
Log.e(TAG, "exception", e);
}
我測試了代碼,它適用於Android 4.4.4。我想知道在其他SDK實現中使用該實現是否安全。
根本不需要使用'onSaveInstanceState()'。見http://stackoverflow.com/questions/24294919/maintain-item-selection-on-orientation-change – faizal