androidandroid-studioxamarin.androidandroid-tvandroid-orientation

Android - How to force Portrait orientation on phone and tablets, but Landscape only on Android TV?


I am developing an Android application in portrait mode like this:

[ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity
{
   // ...
}

It is working fine on all phone and tablet devices, both physical and emulators.

On the other hand, it is working very bad on Android TV emulators. The screen is being cut in half and the application is unusable. However landscape orientation seems good for Android TV format and works fine.

So my question is: is there any way to keep portrait orientation for phone and tablets and use landscape for TV?

I tried to use resources and size qualifiers (like a bool threshold value in res/values-sw1200dp) and then request an orientation change with RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape; but I'm afraid to include also high definition tablets in this way.

Does anyone have a better solution? I am developing in Xamarin.Android, but any solution in Android Studio would also be welcome.


Solution

  • Found a solution myself. I do not want to use sizes as some tablets have better resolution than TVs.

    var res = Application.Context.Resources;
    if (res.DisplayMetrics.DensityDpi == Android.Util.DisplayMetricsDensity.Tv ||
        res.Configuration.UiMode.HasFlag(Android.Content.Res.UiMode.TypeTelevision))
    {
        RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
    }
    

    This is basically the code. Then I used other code tricks like global vars as activity was being recreated if this was called inside onCreate method. Putting this on manifest.xml was not enough.

    android:configChanges="orientation|screenSize"