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

查看:134
本文介绍了活动方向在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"

这确保活动以与上一个活动相同的方向启动.之后,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天全站免登陆