【发布时间】:2013-08-19 19:33:48
【问题描述】:
我有一个在活动中显示全屏位图的应用程序。为了提供快速加载时间,我将它们加载到内存中。但是当屏幕改变方向时,我想清除缓存,以便用适合新尺寸的位图再次填充它。唯一的问题是,为了做到这一点,我需要检测何时发生方向变化。有人知道如何检测吗?
【问题讨论】:
标签: android screen-orientation orientation-changes
我有一个在活动中显示全屏位图的应用程序。为了提供快速加载时间,我将它们加载到内存中。但是当屏幕改变方向时,我想清除缓存,以便用适合新尺寸的位图再次填充它。唯一的问题是,为了做到这一点,我需要检测何时发生方向变化。有人知道如何检测吗?
【问题讨论】:
标签: android screen-orientation orientation-changes
见官方文档http://developer.android.com/guide/topics/resources/runtime-changes.html
更改它实际上会创建一个新视图,并且会再次调用 onCreate。
另外你可以通过
查看@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
【讨论】:
您可以从您的onCreate 方法中检查onSavedInstanceState,如果它不为空,则表示这是配置更改。
【讨论】:
另一种方法是使用OrientationEventListener。
可以这样使用:
OrientationEventListener mOrientationEventListener = new OrientationEventListener(
this, SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
//checking if device was rotated
if (orientationPortrait != isPortrait(orientation)) {
orientationPortrait = !orientationPortrait;
Log.d(TAG, "Device was rotated!");
}
}
};
检查方向:
private boolean isPortrait(int orientation) {
return (orientation >= (360 - 90) && orientation <= 360) || (orientation >= 0 && orientation <= 90);
}
别忘了启用和禁用监听器:
if (mOrientationEventListener != null) {
mOrientationEventListener.enable();
}
if (mOrientationEventListener != null) {
mOrientationEventListener.disable();
}
【讨论】:
通常方向更改会调用OnCreate(),除非您已采取其他措施。
你可以把逻辑放在那里。
【讨论】:
onSavedInstanceState 和stackoverflow.com/questions/4096169/… 的回答