避免ID冲突或重复

问题:

在Fragment或Activity中发生restoreSavedState操作时(比如旋转屏幕),页面中的自定义View,如果有自己复写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()之后,手动设置唯一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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,928评论 0 6
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,936评论 0 0
  • 20年前的今天是我人生的分界线,那之前,是爸爸口中又懒又瘦又近视,就算帮我烧了饼挂在脖子上也会因为不转圈而饿死的小...
    耕云读月阅读 345评论 1 3
  • 今天剽悍晨读分享的书是:《共赢》[美] 约翰·C.麦克斯维尔 《剽悍晨读:共赢—让任何人都无条件支持你的秘诀》 (...
    青城山下雪小蟾阅读 213评论 1 4
  • 天辰十年,冬,大雪。 京城,丞相府。 寒梅蜡雪。 白雪覆盖了整个春熙院,本该是伸手不见五指的黑夜在雪的映衬下犹如白...
    那些年的可爱阅读 1,715评论 15 16