避免ID沖突或重復(fù)

問題:

在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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 9,066評論 0 6
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,995評論 0 0
  • 20年前的今天是我人生的分界線,那之前,是爸爸口中又懶又瘦又近視,就算幫我燒了餅掛在脖子上也會因為不轉(zhuǎn)圈而餓死的小...
    耕云讀月閱讀 366評論 1 3
  • 今天剽悍晨讀分享的書是:《共贏》[美] 約翰·C.麥克斯維爾 《剽悍晨讀:共贏—讓任何人都無條件支持你的秘訣》 (...
    青城山下雪小蟾閱讀 270評論 1 4
  • 天辰十年,冬,大雪。 京城,丞相府。 寒梅蠟雪。 白雪覆蓋了整個春熙院,本該是伸手不見五指的黑夜在雪的映襯下猶如白...
    那些年的可愛閱讀 1,773評論 15 16

友情鏈接更多精彩內(nèi)容