Failed to find style in current theme for custom view with defStyleAttr

266 Views Asked by At

I have a custom view which also uses its own defStyleAttr i.e.

An attribute in the current theme that contains a reference to a style resource that supplies default values for the view.

When declaring this view in a layout file and clicking Preview in Android Studio 2.2.3 I get the following error message:

Missing styles. Is the correct theme chosen for this layout?Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.Failed to find style 'myCustomStyleAttr' in current theme

My view constructors are:

public MyCustomLayout(Context context) {
    this(context, null);
}

public MyCustomLayout(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.myCustomStyleAttr);
}

public MyCustomLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs, defStyleAttr);
}

I know there are a lot of questions on SO with the Missing styles. error however none of the answers worked for me and they were mostly related to AppCompat styles so I wanted to share my solution.

1

There are 1 best solutions below

0
Piotr Zawadzki On

The following worked for me:

public MyCustomLayout(Context context) {
    this(context, null);
}

public MyCustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs, isInEditMode() ? 0 : R.attr.myCustomStyleAttr);
}

public MyCustomLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs, defStyleAttr);
}