0

I have a custom view and I want to make it impossible to change the style on the XML. This is the view

class PrimaryButton @JvmOverloads constructor(
    context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int =
R.attr.primary_button_style
) : MaterialButton(context, attributeSet, R.attr.primary_button_style)

and I want this to be impossible or do nothing.

<com.stuff.buttons.PrimaryButton
          android:id="@+id/first_button"
          android:layout_width="0dp"
          android:layout_height="wrap_content"
          android:text="Primary Button"
          android:layout_margin="16dp"
          style="@style/Small.Secondary.Button"

I want to force always the primary_button_style.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • Does this answer your question? [Custom view style, android's attributes are ignored](https://stackoverflow.com/questions/24182411/custom-view-style-androids-attributes-are-ignored) – Elias Fazel Feb 08 '23 at 17:08
  • not really, I don't have a layout to implement it's just a button with a specific style. no attributes. just the style. – Ricardo Rodrigues Feb 09 '23 at 10:33

1 Answers1

0

In the constructor MaterialButton(context, attributeSet, R.attr.primary_button_style) the primary_button_style is an attribute defined in your app theme, it is not a style.

If you want to apply a different style you have to:

  • Define a custom attribute in attrs.xml
<attr name="primary_button_style" format="reference"/>
  • Assing a style to this attribute in your app theme:
<style name="AppTheme" parent="Theme.Material3.DayNight">
   <item name="primary_button_style">@style/App.Material3.Button</item>
</style>
  • Define the custom style:
    <style name="App.Material3.Button" parent="Widget.Material3.Button">
        <item name="backgroundTint">@color/....</item>
    </style>
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841