Is it possible to StartActivity() from Xamarin.Forms (Shared)?

VanhanenJLAVanhanenJLA Member
edited August 1 in Xamarin.Forms

Recently I've been pondering consistent application UI appearance and run time styling.

I'm somewhat aware that I might be trying to do something silly here, but I've given my attempt at trying to switch the android theme in run time by trying to replace my MainActivity with a separate Activity having a different theme applied via the android ActivityAttribute.

I've also somewhat managed to do this via exposing the MainActivitys ApplicationContext through a static field member and using DependencyService to call a static method onto this context.

[assembly: Xamarin.Forms.Dependency(typeof(ThemingAndroid))]
namespace Sample.Droid.DependencyImplementations
{
    public class ThemingAndroid : ITheming
    {
        public void ChangeTheme()
        {
            MainActivity.ChangeTheme();
        }
    }
}
    public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public static Activity myContext;
        public static void ChangeTheme()
        {
            myContext.StartActivity(new Intent(myContext, typeof(DarkActivity)));
        }
    }

Could this actually work or am I missing something fundamental here?
At the moment I get a null object reference after the new Activity's OnCreate() and LoadApplication() have been executed.

Best Answers

  • Accepted Answer

    I had goofed.

    [Activity(Theme = "@style/MainTheme.Dark")]
        public class DarkActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
        ...
        }
    

    My Activity derived from FormsApplicationActivity rather than AppCompatActivity and I totally missed that.

    Oof.

    Still thanks @Jarvan, I soon found my mistake after trying out your suggestion in an empty project.

Answers

  • VanhanenJLAVanhanenJLA Member
    Accepted Answer

    I had goofed.

    [Activity(Theme = "@style/MainTheme.Dark")]
        public class DarkActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
        ...
        }
    

    My Activity derived from FormsApplicationActivity rather than AppCompatActivity and I totally missed that.

    Oof.

    Still thanks @Jarvan, I soon found my mistake after trying out your suggestion in an empty project.

Sign In or Register to comment.