Dim screen on Android from a form

I now how to dim the screen on Android directly. But how is it done from a form (say a user taps on an on/off switch).

Thank you all.

Best Answers

Answers

  • FrancMoralesFrancMorales JPMember ✭✭

    The code to dim is straightforward:

    var lparams = getWindow().getAttributes();
    
    lparams.screenBrightness = 0.2f ;
    
    getWindow().setAttributes( lparams );
    

    But getWindow() is not recogninzed. I tried including the following without luck:

    using Android.App;
    using Android.Content.PM;
    using Android.OS;
    
  • FrancMoralesFrancMorales JPMember ✭✭

    No, no. That code is in the android project. I based the setup on the one provided for SQLite. An interface has been declared and it can be invoked fine. The problem is with the code above from the android project.

  • FrancMoralesFrancMorales JPMember ✭✭

    I was. Thank you, Adam.

    The full code, still not working, looks like this. I know I'm thick but ???

    using MyApp.Droid;
    using Xamarin.Forms;
    using Android.App;
    using Android.Content.PM;
    using Android.OS;
    using Android.Views;
    
    [assembly: Dependency( typeof( Dim_Android ) )]
    
    namespace MyApp.Droid
    {
        public class Dim_Android : IDim
        {
            public Dim_Android()
            {
            }
    
            public void Dim( float factor )
            {
                var attributes = Window.Attributes;
    
                attributes.ScreenBrightness = factor;
    
                Window.Attributes = attributes;
            }
        }
    }
    

    The error reads

    error CS0120: An object reference is required for the non-static field, method, or property 'Android.Views.Window.Attributes.get'

  • FrancMoralesFrancMorales JPMember ✭✭

    It works. Also tested on device. Thank you, Adam.

    For those slow like me, the code only needs to be changed to:

    var activity = (Activity)Forms.Context;
    var attributes = activity.Window.Attributes;
    
    attributes.ScreenBrightness = factor;
    activity.Window.Attributes = attributes;
    

    Since I have your attention, I want to thank you for the many, many, many times your posts on these forums have allowed me to solve problems that had me spinning my wheels. Good karma to you.

  • adamkempadamkemp USInsider, Developer Group Leader mod

    You're welcome!

Sign In or Register to comment.