vrwim
vrwim

Reputation: 14300

Make singleton of view in android

I have a GUI element in my layout xmls that performs some heavy calculations when it is shown for the first time.

Now I don't want this to happen when I load the view for the second time.

I tried making the constructor private, using the singleton pattern, but then the Inflater doesn't work.

Then I wondered if I could return an existing instance in the constructor, thereby avoiding the problem of a private constructor. (I am using Xamarin C# by the way), but that didn't work.

Is there another way that I can avoid executing the expensive operations repeatedly?

Upvotes: 0

Views: 708

Answers (2)

SKall
SKall

Reputation: 5234

If you don't want to move this to a static class then the quickest way would be to add a static constructor to the view (and mark the variables used as static as well). Here is a quick sample using a static constructor for the MainActivity on a newly created Android application.

[Activity(Label = "App47", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    private static double calculationResult;
    private static bool calculationsDone;

    static MainActivity()
    {
        PerformCalculation().ContinueWith(t =>
        {
            calculationResult = t.Result;
            calculationsDone = true;
        }
        );
    }

    private static Task<double> PerformCalculation()
    {
        var tcs = new TaskCompletionSource<double>();
        tcs.SetResult(10.6);
        return tcs.Task;
    }

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());
    }
}

Upvotes: 1

F43nd1r
F43nd1r

Reputation: 7749

Yes, there is another way:

Do not store the result of your heavy operation inside of the View. Use e.g. a static class for that. Then you can check before starting the operation if there is already something saved in your static class.

Upvotes: 1

Related Questions