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

时间:2011-01-27 08:34:28

标签: android screen-orientation android-3.0-honeycomb

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

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

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

1 个答案:

答案 0 :(得分:8)

你可以combine the orientation and size attributes on the resource objects喜欢:

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

对于较小的屏幕尺寸,请将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;
    }
    [...]
}

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