0

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.

Eselfar
  • 3,759
  • 3
  • 23
  • 43
  • can you check if this solves your problem ? https://stackoverflow.com/questions/4493947/how-to-define-theme-style-item-for-custom-widget – PedroAGSantos Jul 10 '17 at 16:47
  • Thx for your answer. Not really as I don't want to override the theme and I want everything to be managed by the component itself. – Eselfar Jul 10 '17 at 17:21
  • Apparently I misunderstood how it works.The third parameter of the constructor is to defined a custom attribute as the style. So the only constructor which really take a style in parameter is the 4th one (with 4 attribute). But I can't use it as it's Lollipop only and I need to be compatible with at least API 16. :/ – Eselfar Jul 10 '17 at 17:23

0 Answers0