安卓中自定义控件心得(2)--如何获取我们activity根View的背景色,可以用于SurfaceView的背景设置

时间:2022-03-23 22:41:57

直接看代码吧,我用的反射

int childs = ((ViewGroup) getWindow().getDecorView()).getChildCount();
        Drawable mDrawable = (Drawable) getWindow().getDecorView().getBackground();

        if (mDrawable != null) {
            Class<Drawable> mDrawable_class = (Class<Drawable>) mDrawable.getClass();
            try {
                Method[] methods = mDrawable_class.getDeclaredMethods();
                Field mField = mDrawable_class.getDeclaredField("mColorState");
                mField.setAccessible(true);
                Object mColorState = mField.get(mDrawable);
                Class mColorState_class = mColorState.getClass();
                Field mColorState_field = mColorState_class.getDeclaredField("mUseColor");
                mColorState_field.setAccessible(true);
                int color = (int) mColorState_field.get(mColorState);
                String color_str = Integer.toHexString(color);
                count_down_clock.setBackgroundColor(color);
            } catch (Exception e) {

                e.printStackTrace();
            }
        }