的onCreate(...)被调用两次设备旋转后 [英] onCreate(...) is called twice after the device is rotated
问题描述
我有一个关于旋转Android设备的问题。我的code将记录静态和非静态的属性中的onCreate(...)。
进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
公共类MainActivity延伸活动{
静态INT SN;
INT N;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
SN ++;
ñ++;
Log.i(的onCreate的String.Format(SN =%DN =%D,SN,N));
}
}
屏幕方向是纵向。当我第一次跑了code,我得到了:
的onCreate():SN = 1 N = 1
在我旋转屏幕为横向,我得到了:
的onCreate():SN = 2 N = 1
在我再次旋转屏幕为纵向,我得到了:
的onCreate():SN = 3 N = 1
的onCreate():SN = 4 N = 1
我的问题是:
- 如何prevent的onCreate(...)被调用两次当设备旋转回肖像?
- 如何保存非静态变量的值时,该设备旋转?
每当屏幕方向改变时,该活动被破坏,新的活动开始由的onCreate()
方法。
所以每次旋转屏幕,活动会被破坏,新的活动开始由的onCreate()
方法。
您可以通过覆盖的onSaveInstanceState(包B)
方法保存非静态成员。
Android把这种方法每当屏幕旋转,并且,鉴于叠B将被传递给的OnCreate(束B)
从中可以提取您的非静态
成员。
I have a question about rotating the Android device. My code logs a static and non-static attribute in onCreate(...).
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
static int sn;
int n;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sn++;
n++;
Log.i("onCreate", String.format("sn=%d n=%d", sn, n));
}
}
The screen orientation is portrait. When I first ran the code, I got:
onCreate(): sn=1 n=1
After I rotated the screen to landscape, I got:
onCreate(): sn=2 n=1
After I rotated the screen again to portrait, I got:
onCreate(): sn=3 n=1
onCreate(): sn=4 n=1
My questions are:
- How can I prevent onCreate(...) to be called twice when the device is rotated back to portrait?
- How can I save the value of non-static variable when the device is rotated?
Whenever the screen orientation is changed, that Activity is destroyed and a new activity starts by onCreate()
method.
so every time you rotate the screen that activity will be destroyed and a new activity starts by onCreate()
method.
You can save Non Static member by overriding onSaveInstanceState(Bundle b)
method.
Android calls this method whenever the screen is rotated, and that given bundle b would be passed to oncreate(Bundle b)
from which you can extract your non static
member.
这篇关于的onCreate(...)被调用两次设备旋转后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!