I extend from ToggleButton and wanna set my style. Everything works correctly when I set style in xml like style="@style/Button.Filter.Text"
but when I set style programatically in constructor in custom ToggleButton like super(context, attrs, R.style.Button_Filter_Text);
my buttons are styled like normal TextView (probably without style)
Asked
Active
Viewed 1,637 times
2

jakub
- 3,576
- 3
- 29
- 55
2 Answers
1
You can't set style programmatically, the good way is to set style in xml and then inflate it. Take a look in this answer to confirm and second one which describes more ways to do that. And one more example.
-
in this case my Custom Button has to be ViewGroup, because I should add somewhere this inflated ToggleButton. Am I understand correctly? It's quite ugly that I produce unnecessery view layer and structure of my code need to be changed only because of this styling issue. – jakub Apr 30 '15 at 13:12
-
no `Button` is a `View` and you will have to add it to parent, `ViewGroup`. This is ugly I agree. Also if I understood purpose properly you can make a `selector` in `drawable` and set some style as background. This is from "second one" answer. – Yurets Apr 30 '15 at 13:19
-
1Ok, I changed structure of my custom view and wrap ToggleButton into FrameLayout ugly, but versatile in this case. Cheers for info that I can't do it programatically. – jakub Apr 30 '15 at 13:49
1
Parameter int defStyleAttr
in three-argument constructor may not work with the custom styles. From the Android documentation:
defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
To workaround this case use such approach:
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.Button_Filter_Text);
View view = new View(wrappedContext, null, 0);
Or if you support just LOLLIPOP and higher there is a use constructor with 4 parameters:
View (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Where defStyleAttr
should be 0 and defStyleRes
is your style ID

DmitryArc
- 4,757
- 2
- 37
- 42