0

Please help me out of the insanity!

The code below works and sets the background of my custom view as I want:

public class MyLayout extends LinearLayout {

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs, 0, R.style.MyStyle);
    }

    //Omissions

}

But it gives:

Call requires API level 21 (current min is 19): new android.widget.LinearLayout

I did some code which manually extracts the attributes from the style, but it is not dynamic - so if the style changes later by adding attributes, things will have to be maintained.

I've read the quote below, but do not quite understand the interaction with the 'theme':

defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies defaults values for the StyledAttributes. Can be 0 to not look for defaults.

defStyleRes A resource identifier of a style resource that supplies default values for the StyledAttributes, used only if defStyleAttr is 0 or cannot be found in the theme. Can be 0 to not look for defaults.

The following does nothing:

public class MyLayout extends LinearLayout {

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs, R.style.MyStyle);
    }

    //Omissions

}

What have I done wrong? How do I simply style my custom component with a background color?

Adam
  • 2,845
  • 2
  • 32
  • 46
  • I read this: https://stackoverflow.com/questions/4493947/how-to-define-theme-style-item-for-custom-widget?utm_medium=organic&utm_source=google_rich_qa I hope that is not the way forward; I do not think that is viable in my situation – Adam Apr 26 '18 at 08:06
  • 1
    Yeah, that's basically how the `defStyleAttr` parameter is meant to be used. Why is it not viable for you? You just need to add an `` in your resources, set its value to `MyStyle` in your theme, and pass the `R.attr` as the third parameter in the `super` constructor call. – Mike M. Apr 26 '18 at 08:15
  • Doing a test implementation of it now, we'll see how it goes, So many hoops! Do you know if there is any disadvantages to the solution i have which requires api 21? – Adam Apr 26 '18 at 08:18
  • 1
    Pretty much just the fact that the min API is 21. It's a real pain that it wasn't introduced earlier, especially considering that that's what a lot of developers think `defStyleAttr` actually is anyway. We've got answers here with 100+ votes that show an `R.style` passed for that parameter, so it seems it's caused confusion for quite some time. I agree, though, that it wasn't a great way to do that in the first place. – Mike M. Apr 26 '18 at 08:24
  • 1
    Ok! Thanks. Yes I found some very confusing information on this. And yes, it does work in my situation. Though I find it very silly indeed... But hey it works ^^ ... – Adam Apr 26 '18 at 08:30

0 Answers0