Android:避免从其他活动返回时调用onCreate() [英] Android: avoid calling onCreate() when back from another activity

查看:250
本文介绍了Android:避免从其他活动返回时调用onCreate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的应用程序包含两个活动A和B. 两者都限于AndroidManifest中的肖像.

Assume my application contains two activity, A and B. Both are limited to portrait in AndroidManifest.

活动A启动了活动B. 在活动B中,有一个按钮,单击该按钮将调用finish().

Activity A started Activity B. In Activity B, there is a button, which calls finish() when clicked.

问题是... 当我垂直握住设备(人像)并单击按钮时,调用顺序为

The problem is... When I hold the device vertically(portrait) and click the button, the calling sequence is

B.onStop();
B.onDestory();
A.onStart();

但是,当我水平握住设备(横向)时,序列变为

However, when I hold the device horizontally(landscape), the sequence becomes

B.onStop();
B.onDestory();
A.onCreate();
A.onStart();

我不想要A.onCreate() !!!

我尝试按下Back按钮. A.onCreate()不被调用. 所以...模拟Back按钮是解决问题的方法

I tried pressing the Back button. A.onCreate() is not called. So... simulating the Back button is somehow the solution

我尝试了以下方法,所有这些方法都称为A.onCreate().

I have tried the followings, all of them called A.onCreate()..

finish();

.

onBackPressed()

.

dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

已编辑

我必须再说一遍. 这两项活动都限于AndroidManifest中的肖像. onConfigurationChanged永远不会被调用.

I have to say again. Both activities are limited to portrait in AndroidManifest. onConfigurationChanged is never called.

不接受静态变量.因为这会导致其他问题.

Static variable is not accepted. Since this will cause other problem..

推荐答案

之所以会发生这种情况,是因为在启动应用程序imo的某个阶段更改了方向.
更改方向后,活动将被销毁,然后重新创建.为避免它处理方向.

在活动下的清单文件中添加以下行,即可自己处理方向更改.

It happens because you have changed the orientation at some stage when the application has started, imo.
On orientation change the activity is destroyed then recreated. To avoid it handle the orientation.

Handle the orientation change by yourself by adding the following line in the manifest file , under activity.

<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden|screenSize"

这篇关于Android:避免从其他活动返回时调用onCreate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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