1
votes

In my Xamarin Forms Android app, I would like to change the color of the splash screen based on a theme that the user has selected at run time. This change should impact the next run of the app.

I have tried using the built in splash_screen.xml and using a Splash.axml file, but I cannot figure out how (if possible) to set the background color of the splash screen to a color defined in a theme.

Is this possible?

2

2 Answers

0
votes

I have tried using the built in splash_screen.xml and using a Splash.axml file, but I cannot figure out how (if possible) to set the background color of the splash screen to a color defined in a theme.

You can define themes for your splashScreen and then set android:windowBackground to a specific color:

styles.xml:

<resources>
  <style name="AppTheme">
    <item name="android:windowBackground">@color/colorPrimary</item>
    <item name="android:windowNoTitle">true</item>
  </style>
  <style name="AppTheme2">
    <item name="android:windowBackground">@color/colorAccent</item>
    <item name="android:windowNoTitle">true</item>
  </style>
  ...
</resources>

SplashScreen.cs( don't forget to set SplashScreen activity to be mainlauncher):

[Activity(Label = "SplashActivity",MainLauncher =true)]
public class SplashActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        ISharedPreferences preferences=GetSharedPreferences("SplashThemeId", FileCreationMode.Private);
        var themeName=preferences.GetString("themeName","AppTheme");
        int themeId = Resource.Style.AppTheme ;
        switch (themeName)
        {
            case "AppTheme":
                themeId = Resource.Style.AppTheme;
                break;
            case "AppTheme2":
                themeId = Resource.Style.AppTheme2;
                break;
        }
        SetTheme(themeId);
        base.OnCreate(savedInstanceState);
        ...

As you noticed, I use SharedPreference to store the user selected Theme in Runtime. You can also use Android Settings for the same purpose.

Here is the complete demo. It's native android project, but it's the same for forms project.

0
votes

After all of the research I've done and the things I've tried in code, I am concluding that it is not possible to dynamically set the color of the initial activity. I am going with a neutral color for the splash.