Android应用程序开发:处理屏幕方向更改 [英] Android App Development: Handling Screen Orientation Changes

查看:139
本文介绍了Android应用程序开发:处理屏幕方向更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经运行与处理屏幕方向变化(例如:纵向到横向)的问题。我正在开发一个手电筒应用程序,它具有一个切换按钮开启LED灯开启或关闭该人的手机上。设置我的onPause()方法来杀应用程序,如下所示:         

I have run into a problem with handling screen orientation changes (For example: portrait to landscape). I'm developing a flashlight app which has a toggle button that turns the LED light on or off on the person's phone. I set up my onPause() method to kill the app like so:

    @Override
    protected void onPause() {
         super.onPause();
         finish();
    }

这是因为如果我打开应用程序,然后去别的东西(比如开放的YouTube),然后再回来和preSS按钮再次崩溃。但由于这个完成();的事情,因为很明显当切换方向,它调用的onPause()方法,完成我不能处理屏幕方向的变化!

This is because if I was to open the app and then go something else (like open youtube) and then come back and press the button again it crashes. But because of this "finish();" thing I can't handle screen orientation changes because apparently when it switches orientation it calls the onPause() method which finishes!

所以我的问题是...我怎么办两者兼而有之?我希望能够解决死机问题,但也没有它崩溃时,屏幕方向变化。我不要求为code(尽管这将是有益的),刚刚从一个新的一双眼睛的一些见解。

SO my question is...how do I do both? I want to be able to fix the crash problem but also not have it crash when the screen orientation changes. I'm not asking for code (although it would be helpful) just some insight from a new set of eyes.

我想过用一个如果的声明......将这项工作?

I thought about using an "if" statement...would this work?

在此先感谢, 安德鲁

推荐答案

在屏幕方向的变化,该活动会做的onPause()的onStop()和的onCreate(再次)。如果你不希望你的活动做的onPause时的方向变化,试试这个:

When the screen orientation changes, the activity will do onPause(), onStop() and onCreate() again. If you don't want your activity do onPause when the orientation changes, try this:

  1. 在你的manifest.xml,增加机器人:configChanges = |像你的活动的方向keyboardHidden:

  1. In your manifest.xml, add android:configChanges="orientation|keyboardHidden" for your activity like:

<activity android:name=".yourname"
          android:configChanges="orientation|keyboardHidden">
</activity>

  • 在你的活动,重写此方法:

  • In your activity, override this method:

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    

  • 不过,我的建议是不要用完成()的onPause(),该系统可以处理生命周期正好。如果你想完成你的活动时,家庭或后退按钮pressed,尽量覆盖 onBack preSS() onUserLeaveHint( ),这两种方法可以捕捉背部和主页按钮pressed,并在这两个方法中添加完成()

    But my advice is not to use finish() in onPause(), the system can handle the lifecycle just fine. If you want to finish your activity when the home or back button pressed, try to override onBackPress() and onUserLeaveHint(), these two method can catch back and home button pressed, and add finish() in these two method.

    希望它帮助。

    这篇关于Android应用程序开发:处理屏幕方向更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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