5

我有一个在活动中显示全屏位图的应用程序。为了提供快速加载时间,我将它们加载到内存中。但是当屏幕改变方向时,我想清除缓存以便用适合新尺寸的位图再次填充它。唯一的问题是,为了做到这一点,我需要检测何时发生方向变化。有谁知道如何检测到这个?

4

4 回答 4

23

查看官方文档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();
    }
}
于 2013-08-19T19:38:52.633 回答
4

您可以onSavedInstanceState从您的onCreate方法中检查,如果它不为空,则表示这是配置更改。

于 2013-08-19T19:46:13.240 回答
4

另一种方法是使用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();
    }
于 2016-04-01T10:49:48.927 回答
2

通常方向更改调用OnCreate(),除非您已经做了一些事情以使其不这样做。

你可以把逻辑放在那里。

于 2013-08-19T19:36:40.413 回答