Add custom theme in application?

709 views Asked by At

I am building an android application. Where I am adding custom theme Color(Blue, Red, Yellow ETC) which can be choose by users.

I am able to apply custom theme for my view, text and icon. The challenging part is to add different color for primary button and secondary button for single theme.

Example - For Blue theme Primary Button: bg - Blue, text - White Seconry color: bg - White, border and text as red

Custom Style

<style name="AppThemePurple" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimaryPurple</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDarkPurple</item>
    <item name="colorAccent">@color/colorAccentPurple</item>
</style>
2

There are 2 answers

0
Gabe Sechan On

Android really isn't set up for doing either of those things automatically. There's no way to change a theme at runtime. The only time you can set a theme is when you inflate the layout. To do so, instead of using the normal inflate command, use

LayoutInflater.from(new ContextThemeWrapper(baseContext, themeId), R.layout.layoutId)

Then to change the theme, you'd have to restart the activity with activity.recreate() and store the theme id you want to use in a static variable it can access. This will kill the current instance of the Activity and create a new one. Of course this would require you to have all these themes pre-defines, and you'd need to create styles for the buttons that reference those themes variables, and apply the correct styles to the buttons in the xml. The system really isn't meant for changing themes, its meant for you to have a single theme per activity and stick to it.

1
Narendra_Nath On

Set the materialButtonStyle to AppThemePurple

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="materialButtonStyle">@style/AppThemePurple</item>
</style>