【问题标题】:Disabling the rotation on a tablet禁用平板电脑上的旋转
【发布时间】:2019-11-19 14:01:19
【问题描述】:

我的应用为手机启用了旋转,但我不想在平板电脑中使用横向模式。

我试过了

<activity 
    android:screenOrientation="portrait" />

但这并没有只为平板电脑指定纵向模式。

【问题讨论】:

    标签: android android-layout layout


    【解决方案1】:

    我认为您需要以编程方式进行,我认为清单没有任何属性可以设置它。

    第一步检测平板电脑中安装的应用,如下所示:

    Java:

     public boolean isTablet(Context context) {
            boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
            boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
            return (xlarge || large);
        }
    

    科特林

    fun isTablet(context: Context): Boolean {
            val xlarge = context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK === Configuration.SCREENLAYOUT_SIZE_XLARGE
            val large =
                context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK === Configuration.SCREENLAYOUT_SIZE_LARGE
            return xlarge || large
        }
    

    Kotlin 扩展:

        fun Context.isTablet(): Boolean {
            val xlarge = resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK === Configuration.SCREENLAYOUT_SIZE_XLARGE
            val large =
                resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK === Configuration.SCREENLAYOUT_SIZE_LARGE
            return xlarge || large
        }
    

    第二步,在onCreate中改一下:

    Java

    
    if(isTablet(this)){
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    
    

    Kotlin 扩展

      override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            if(isTablet()){
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }
    

    【讨论】:

    • 说真的,我从来没有想过,非常感谢。 @米格尔
    【解决方案2】:

    您可以从代码中设置它,但也可以仅在 XML 文件中使用它,但诀窍是使用 resource qualifiers 并为您所谓的平板电脑设置单独的 XML,或者为平板电脑设置单独的样式并应用该样式到活动。

    【讨论】:

    • 但即使我只有纵向布局,我的应用程序仍然可以在平板电脑上旋转。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2012-03-22
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多