I'm creating a custom view by extending a LinearLayout. If the user doesn't specify a style I want to use a default one. The default style is supposed to set a custom background to the LinearLayout. But it doesn't work.
Here is my code:
public class CustomLinearLayout extends LinearLayout {
public CustomLinearLayout(Context context) {
this(context, null, R.style.CustomStyle);
}
public CustomLinearLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.style.CustomStyle);
}
public CustomLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr != 0 ? defStyleAttr : R.style.CustomStyle);
init(context, attrs);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, (defStyleAttr != 0 ? defStyleAttr : R.style.CustomStyle), defStyleRes);
init(context, attrs);
}
// ...
}
And the custom style:
<style name="CustomStyle">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/default_background</item> <!-- The background is a shape defined in an XML file -->
</style>
What have I done wrong and what should I do to solve this issue?
If I call setBackgroundResource(R.drawable.default_background)
in the constructor, it works but this is NOT what I want.