I'm trying to create my own button based on android.widget.Button
. But when I set style attribute programmatically, I'm getting this Rendering Problem:
Failed to find style 'My_Button' in current theme
However set style in xml is work.
Am I missing something?
activity_main.xml
<com.myapp.Components.Button
android:id="@+id/xx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="touch_"
app:_icon=""/>
<com.myapp.Components.Button
style="@style/My_Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="touch"
app:_icon=""/>
Button.java
public class Button extends android.widget.Button {
public Button(@NonNull Context context) {
super(context, null, R.style.My_Button);
init(context, null);
}
public Button(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs, R.style.My_Button);
init(context, attrs);
}
public Button(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, R.style.My_Button);
init(context, attrs);
}
// ... more
}
styles.xml
<style name="My_Button" parent="Base.Widget.AppCompat.Button.Borderless">
<item name="android:foreground">?android:attr/selectableItemBackground</item>
<item name="android:background">#592612</item>
<item name="android:gravity">center</item>
</style>
Finally, I have found the answer!
Replace:
super(context, attrs, R.style.My_Button);
with super(context, attrs, R.attr.ButtonStyle);
In styles.xml add
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="ButtonStyle">@style/Button_Style</item>
...
</style>
In attrs.xml add
<declare-styleable name="Theme">
<attr name="ButtonStyle" format="reference"/>
</declare-styleable>