我注意到在处理来自 Activity 的配置更改时,从横向->纵向或纵向->横向更改方向后,onLayout 和 onSizeChanged 会立即连续调用两次。此外,第一个 onLayout/onSizeChanged 包含旧尺寸(旋转之前),而第二个 onLayout/onSizeChanged 包含新(正确)尺寸。
有谁知道为什么,和/或如何解决这个问题?似乎屏幕尺寸的变化可能在配置更改后的一段时间内发生 - 即,在onConfigurationChanged
调用配置更改后尺寸不正确?
这是下面代码的调试输出,显示了从纵向旋转到横向后的 onLayout/onSizeChanged 调用(注意设备为 540x960,因此横向宽度应为 960,而纵向宽度为 540):
03-13 17:36:21.140: DEBUG/RotateTest(27765): onConfigurationChanged: LANDSCAPE
03-13 17:36:21.169: DEBUG/RotateTest(27765): onSizeChanged:540,884,0,0
03-13 17:36:21.189: DEBUG/RotateTest(27765): onLayout:true-0,0,540,884
03-13 17:36:21.239: DEBUG/RotateTest(27765): onSizeChanged:960,464,540,884
03-13 17:36:21.259: DEBUG/RotateTest(27765): onLayout:true-0,0,960,464
另请注意,第一个 onSizeChanged oldwidth 和 oldheight 为 0,表明我们刚刚添加到视图层次结构中 - 但横向尺寸错误!
这是说明这种行为的代码:
我的活动.java
package com.example;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
public class MyActivity extends Activity
{
private static String TAG = "RotateTest";
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged: " + (newConfig.orientation == 1 ? "PORTRAIT" : "LANDSCAPE"));
super.onConfigurationChanged(newConfig);
_setView();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
_setView();
}
private void _setView() {
MyHorizontalScrollView scrollView = new MyHorizontalScrollView(this, null);
setContentView(scrollView);
}
}
MyHorizontalScrollView.java
package com.example;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.HorizontalScrollView;
public class MyHorizontalScrollView extends HorizontalScrollView {
private static String TAG = "RotateTest";
public MyHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
Log.d(TAG, "onLayout:" + String.format("%s-%d,%d,%d,%d", changed, l, t, r, b));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.d(TAG, "onSizeChanged:" + String.format("%d,%d,%d,%d", w, h, oldw, oldh));
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="9"/>
<application android:label="@string/app_name"
>
<activity android:name="MyActivity"
android:label="@string/app_name"
android:configChanges="orientation"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>