在Android上为手机和平板电脑设置不同的方向

And*_*ast 3 android screen-orientation android-orientation

我想在我的应用程序中执行以下操作:

  • 仅适用于手机的人像模式
  • 平板电脑的纵向模式和横向模式.

我知道我可以轻松更改清单文件中的方向,但这会影响整个应用程序.

我还想过创建单独的活动,处理不同的版本,但我不知道如何使用应用程序检测设备的类型.

有谁知道如何解决这个问题?

Him*_*ani 9

您可以使用以下代码区分正常/大屏幕并相应地阻止方向更改.

public static boolean isTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
Run Code Online (Sandbox Code Playgroud)


Egi*_*gis 6

在活动的onCreate方法中,检查应用程序是在手机上还是在平板电脑上运行.如果应用程序正在手机设置活动屏幕方向上运行,则仅限肖像.

将这些文件添加到您的res文件夹.

RES /值/ vars.xml:

<?xml version="1.0" encoding="utf-8"?><resources><bool name="is_tablet">false</bool></resources>
Run Code Online (Sandbox Code Playgroud)



RES /值-sw600dp/vars.xml:

<?xml version="1.0" encoding="utf-8"?><resources><bool name="is_tablet">true</bool></resources>
Run Code Online (Sandbox Code Playgroud)

在onCreate方法关闭所有活动时添加以下代码:

    if (!getResources().getBoolean(R.bool.is_tablet)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
Run Code Online (Sandbox Code Playgroud)