Skip to content

Instantly share code, notes, and snippets.

@SIDOVSKY
Last active January 19, 2023 04:00
Show Gist options
  • Save SIDOVSKY/52f2509988030282103fadf3d0255396 to your computer and use it in GitHub Desktop.
Save SIDOVSKY/52f2509988030282103fadf3d0255396 to your computer and use it in GitHub Desktop.
Custom view default style overload example
package <yourpackage>
import android.content.Context
import android.util.AttributeSet
import androidx.annotation.AttrRes
import com.google.android.material.button.MaterialButton
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
// redefine the attribute so that the default style can be controlled from the theme, and also overridden in the xml layout via style="@style/..."
@AttrRes defStyleAttr: Int = R.attr.customButtonStyle
) : MaterialButton(
context.apply {
// in case R.attr.customButtonStyle wont be defined in the main theme
theme.applyStyle(R.style.CustomButtonThemeDefault, false)
},
attrs,
defStyleAttr
)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="customButtonStyle" format="reference"/>
<style name="CustomButtonThemeDefault">
<item name="customButtonStyle">@style/CustomButtonStyle</item>
</style>
<style name="CustomButtonStyle" parent="Widget.MaterialComponents.Button">
<!-- Styling by default -->
</style>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment