文章

自定义View预览

自定义View预览

自定义 View 预览

isInEditMode

RecyclerView:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private void createLayoutManager(Context context, String className, AttributeSet attrs,  
        int defStyleAttr, int defStyleRes) {  
    if (className != null) {  
        className = className.trim();  
        if (!className.isEmpty()) {  
            className = getFullClassName(context, className);  
            try {  
                ClassLoader classLoader;  
                if (isInEditMode()) {  
                    // Stupid layoutlib cannot handle simple class loaders.  
                    classLoader = this.getClass().getClassLoader();  
                } else {  
                    classLoader = context.getClassLoader();  
                }  
                Class<? extends LayoutManager> layoutManagerClass =  
                        Class.forName(className, false, classLoader)  
                                .asSubclass(LayoutManager.class);  
                Constructor<? extends LayoutManager> constructor;  
                Object[] constructorArgs = null;  
                try {  
                    constructor = layoutManagerClass  
                            .getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE);  
                    constructorArgs = new Object[]{context, attrs, defStyleAttr, defStyleRes};  
                } catch (NoSuchMethodException e) {  
                    try {  
                        constructor = layoutManagerClass.getConstructor();  
                    } catch (NoSuchMethodException e1) {  
                        e1.initCause(e);  
                        throw new IllegalStateException(attrs.getPositionDescription()  
                                + ": Error creating LayoutManager " + className, e1);  
                    }  
                }  
                constructor.setAccessible(true);  
                setLayoutManager(constructor.newInstance(constructorArgs));  
            } catch (ClassNotFoundException e) {  
            // ... 
        }  
    }  
}

报错的地方,用 isInEditMode 过滤掉:

image.png

解决:

image.png

技巧

不要用静态的 Context

如:

  • AppContext.application
  • 获取资源
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ViewUtils
public static int getColor(@ColorRes int idRes) {
	try {
		return ContextCompat.getColor(AppContext.application, idRes);
	} catch (Exception e) {
		e.printStackTrace();
		return Color.TRANSPARENT;
	}
}

// 原本
color = ViewUtils.getColor(AppContext.application, R.color.sui_color_white_alpha10)
// 改成:
color = ContextCompat.getColor(context, R.color.sui_color_white_alpha10)
本文由作者按照 CC BY 4.0 进行授权