利用反射 获取android布局文件中设置的属性值

来源:互联网 发布:软件企业网址 编辑:程序博客网 时间:2024/05/16 18:50
    private void initSystemAttrs(Context context, AttributeSet attrs) {        if (attrs == null) {            return;        }        Class<?> clazz = ReflectUtils.getClass("com.android.internal.R$styleable");        if (clazz == null) {            return;        }        int[] getViewGroupStyleable = getStaticIntArrayField(clazz, "ViewGroup_Layout");        if (getViewGroupStyleable == null) {            return;        }        try {            TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attrs, getViewGroupStyleable);            int layoutWidthIndex = getStaticIntField(clazz, "ViewGroup_Layout_layout_width");            int layoutHeightIndex = getStaticIntField(clazz, "ViewGroup_Layout_layout_height");            int layout_width= obtainStyledAttributes.getLayoutDimension(layoutWidthIndex, "layout_width");            int layout_height= obtainStyledAttributes.getLayoutDimension(layoutHeightIndex, "layout_height");            obtainStyledAttributes.recycle();        } catch (Exception e) {            LogUtils.e(e);        }    }    public static Class<?> getClass(String className) {        try {            Class<?> forName = Class.forName(className);            return forName;        } catch (Exception e) {            LogUtils.e(e);        }        return null;    }    public static int[] getStaticIntArrayField(Class<?> clazz, String fieldName) {        try {            Field declaredField = clazz.getDeclaredField(fieldName);            declaredField.setAccessible(true);            Object object = declaredField.get(null);            int[] result = (int[]) object;            return result;        } catch (Exception e) {            LogUtils.e(e);        }        return null;    }       public static int getStaticIntField(Class<?> clazz, String fieldName) {        try {            Field declaredField = clazz.getDeclaredField(fieldName);            declaredField.setAccessible(true);            Object object = declaredField.get(null);            int result = (int) object;            return result;        } catch (Exception e) {            LogUtils.e(e);        }        return Integer.MIN_VALUE;    }
0 0
原创粉丝点击