美文网首页
避免ID冲突或重复

避免ID冲突或重复

作者: CaiBird | 来源:发表于2016-10-25 10:55 被阅读492次
    问题:

    在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

    相关文章

      网友评论

          本文标题:避免ID冲突或重复

          本文链接:https://www.haomeiwen.com/subject/nndruttx.html