是否有可能在某些屏幕尺寸上支持两种方向而不支持其他尺寸?

Jon*_*son 3 android screen-orientation android-3.0-honeycomb

在我的应用程序中,我目前仅支持某些活动的纵向方向,因为我认为大多数手机用户大多数时间都会使用纵向(并用一只手握住设备).

然而,在新的Honeycomb平板电脑上,用户似乎可能更频繁地使用横向,所以我想支持更多我的活动的两种方向.

我宁愿不必回去为较小的屏幕尺寸添加横向布局(一直到QVGA),所以我想知道是否有一种方法只支持xlarge屏幕类型的景观,但不是其他.

Hei*_*upp 8

您可以在资源对象上组合方向和大小属性,如:

res/layout/             -- default
res/layout-port/        -- portrait for any screen size
res/layout-xlarge/      -- any orientation on xlarge screens
res/layout-xlarge-land/ -- landscape on xlarge screens
Run Code Online (Sandbox Code Playgroud)

使用layout-port您的唯一肖像的布局目录较小的屏幕尺寸,然后添加你的XLARGE布局的layout-xlarge目录,如果你想使用相同的布局文件纵向和横向上XLARGE,或layout-xlarge-landlayout-xlarge-port,如果你想根据不同的布局文件方向.

然后,当您在较小屏幕的设备上旋转到横向时,操作系统将尝试加载横向布局但失败,因为没有匹配并抛出一个Resources.NotFoundException.但是,您可以捕获该异常,并在这些情况下强制将活动设置为纵向模式Activity.setRequestedOrientation():

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        setContentView(R.layout.titlescreen);
    } catch (Resources.NotFoundException e) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        return;
    }
    [...]
}
Run Code Online (Sandbox Code Playgroud)

然后,这将导致在纵向模式下重新创建活动,并且它不会尝试再次更改,因为使用setRequestedOrientation()覆盖方向传感器.