活动方向在 Android 上自动更改 [英] Activity orientation changes automatically on Android

查看:23
本文介绍了活动方向在 Android 上自动更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 minSdkVersion=15 开发基于 Android 的移动应用程序.我想支持平板电脑的两种方向,而智能手机只支持纵向.一切都像魅力一样,但我遇到了一个让我发疯的小错误.当智能手机处于横向模式并且我尝试触发新活动时,它会以横向模式打开一段时间,然后自动旋转为纵向.我的每一个活动都扩展了一个 GeneralActivity 类:

I'm developing a mobile application based on Android with minSdkVersion=15. I would like to support both orientations for tablets and only portrait for smartphones. Everything works like a charm but I'm experiencing a little bug that is driving me crazy. When smartphone is in landscape mode and I try to trigger a new Activity, it opens in landscape mode for a while and then autorotates to portrait. Each one of my activities extend a GeneralActivity class:

public class GeneralActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If smartphone lock orientation to portrait
        if (!Helper.isTablet(this.getApplicationContext())){
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}

我使用此功能检测平板电脑:

I detect tablets with this function:

public class Helper {
    public static boolean isTablet(Context context){
        Configuration config = context.getResources().getConfiguration()
        return config.smallestScreenWidthDp >= 600;
    }
}

我选择不在 Manifest.xml 中指定 android:screenOrientation 因为这样我就能够支持平板电脑的所有界面方向.我错过了什么吗?

I choose not to specify android:screenOrientation inside Manifest.xml because in that way I'm able to support all interface orientation for tablets. Am I missing something?

编辑

我决定应用 Jonathan 在答案中建议的最佳实践,但我描述的问题仍然存在.这是我在 github 上的仓库:https://github.com/giacmarangoni/Android-Orientation-Test

I decided to apply the best practice suggested in the answer by Jonathan, but the issue I described is still here. Here's my repo on github: https://github.com/giacmarangoni/Android-Orientation-Test

推荐答案

我在 Android N & 上遇到了同样的问题O 并找到了解决方案.

I had the same problem on Android N & O and found a solution.

我仍然在 onCreate 方法中使用 setRequestedOrientation,但我已经为清单中的每个活动添加了这个:

I still use setRequestedOrientation in the onCreate method, but I've added this for every activity in the manifest:

android:screenOrientation="behind"

这可确保 Activity 以与前一个 Activity 相同的方向启动.之后的 setRequestedOrientation 将覆盖它,但如果它与之前的活动相同,您将不会看到作为用户的任何变化.

This makes sure that the activity launches with the same orientation as the previous activity. The setRequestedOrientation afterwards will override it, but if it's the same as the previous activity you don't see anything change as the user.

这篇关于活动方向在 Android 上自动更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆