【问题标题】:Portrait mode for Phones/Tablets and Landscape mode for Android TV?手机/平板电脑的纵向模式和 Android TV 的横向模式?
【发布时间】:2016-12-12 22:13:38
【问题描述】:

我的应用设计为在手机和平​​板电脑中使用纵向模式。我正在尝试支持需要横向模式的 Android TV,因此我的应用现在根据设备是否为 Android TV 使用不同的布局。

问题在于 Google 拒绝来自 Android TV 的使用“纵向”功能的应用。如何为手机/平板电脑保留“纵向”,并仅为具有相同 APK 的电视切换到横向?这样做是制作两个不同的 APK 的唯一方法吗?如果可能的话,我想避免这种情况。

PS。我正在使用 Unity 3D,这可能会限制一些更晦涩的解决方案。

【问题讨论】:

    标签: android android-layout unity3d


    【解决方案1】:

    您可以根据设备是手机/平板电脑还是电视,通过代码设置屏幕模式。

    第一步是检查此应用程序是否在电视或移动设备上运行。在 Android 上没有官方 API 可以执行此操作,但 this 帖子描述了如何使用 AndroidJavaClass 作为插件来执行此操作。

    bool isAndroidTv()
    {
        #if !UNITY_ANDROID || UNITY_EDITOR
        return false;
        #else
    
        AndroidJavaClass unityPlayerJavaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject androidActivity = unityPlayerJavaClass.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaClass contextJavaClass = new AndroidJavaClass("android.content.Context");
        AndroidJavaObject modeServiceConst = contextJavaClass.GetStatic<AndroidJavaObject>("UI_MODE_SERVICE");
        AndroidJavaObject uiModeManager = androidActivity.Call<AndroidJavaObject>("getSystemService", modeServiceConst);
        int currentModeType = uiModeManager.Call<int>("getCurrentModeType");
        AndroidJavaClass configurationAndroidClass = new AndroidJavaClass("android.content.res.Configuration");
        int modeTypeTelevisionConst = configurationAndroidClass.GetStatic<int>("UI_MODE_TYPE_TELEVISION");
    
        return (modeTypeTelevisionConst == currentModeType);
        #endif
    }
    

    然后你可以在Awake函数中用Screen.orientation改变屏幕方向:

    void Awake()
    {
        bool androidTv = isAndroidTv();
        Screen.autorotateToLandscapeLeft = androidTv;
        Screen.autorotateToLandscapeRight = false;
        Screen.autorotateToPortrait = !androidTv;
        Screen.autorotateToPortraitUpsideDown = false;
    
        if (androidTv)
        {
            Screen.orientation = ScreenOrientation.LandscapeLeft;
        }
        else
        {
            Screen.orientation = ScreenOrientation.Portrait;
        }
    }
    

    您可以在设置为通过脚本顺序设置提前运行的“游戏控制器”对象中使用它。

    此外,您还需要将 Android 播放器设置为将默认方向设置为自动旋转。

    【讨论】:

    • 这是否需要在播放器设置中将“默认方向”设置为自动?如果是这样,当用户旋转手机时手机会改变方向吗?
    • “这需要在播放器设置中将“默认方向”设置为自动吗?”我不确定。您可以立即使用 Android 设备对其进行测试,看看会发生什么。 “如果是这样,当用户旋转手机时手机会改变方向吗?”同样,你必须尝试看看当用户旋转手机时它是否会改变。如果发生这种情况,您可以使用我的解决方案here 来解决该问题。设置方向后调用该函数即可。
    • 好。当用户旋转手机时它会改变方向吗?
    • 不,如果我将这些 autorotateToLandscapeLeft 属性设置为 false,则不会。
    • 很高兴知道。编码愉快!
    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2014-03-14
    • 2017-04-12
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多