問題:
在Fragment或Activity中發(fā)生restoreSavedState操作時(比如旋轉(zhuǎn)屏幕),頁面中的自定義View,如果有自己復(fù)寫onSaveInstanceState方法,且該自定義View是以addView()的形式添加的,就有可能造成以下報錯:
java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class *.waveswiperefreshlayout.WaterWave$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/swipe_refresh_layout.
解決辦法:
在addView()之后,手動設(shè)置唯一ID,代碼如下:
private void setWaterWaveId() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mWaterWave.setId(View.generateViewId());
} else {
mWaterWave.setId(AppUtils.generateViewId());
}
}
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
/**
* Generate a value suitable for use in View.setId(int).
* This value will not collide with ID values generated at build time by aapt for R.id.
*
* @return a generated ID value
*/
public static int generateViewId() {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
參考:
Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Wrong State Class,expecting View State but received class...異常解決思路之一
Wrong state class, expecting View State but