且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

屏幕方向更改后应用程序崩溃

更新时间:2022-02-02 23:47:07

我发现了,我错过了什么 :) 既然没人回答,我给大家留个答案,遇到同样问题的人.

I've found out, what did I missed :) Since no one answered, I'll leave an answer for everyone, who'll encounter the same problem.

事实证明,所描述的问题是一个众所周知的 Android 库错误:ViewFlipper 无法正确处理屏幕方向更改.它出现在 API 2.1 中并一直持续到 3.0,据信它已修复.不幸的是,今天的大多数智能手机都存在这个问题,因为它们通常搭载 2.2 或 2.3.

It turns out, that the problem described is a generally known Android libraries bug: ViewFlipper fails to handle screen orientation change properly. It have appeared in API 2.1 and continues until 3.0, where it is believed to be fixed. Unfortunatelly, most of today's smartphones suffer from this problem, as usually they have 2.2 or 2.3 onboard.

解决方案是手动处理屏幕方向更改(请参阅 Activity 在 Android 旋转时重启 ) 或使用 FrameLayout、视图可见性和动画类手动实现视图更改和动画.

The solution is either to handle screen orientation change manually (see Activity restart on rotation Android ) or implement the view changes and animations manually, using FrameLayout, view visibility and animation classes.

另一种是使用 Eric Burke 的 SafeViewFlipper 类:

Another one is to use Eric Burke's SafeViewFlipper class:

/**
 * Works around Android Bug 6191 by catching IllegalArgumentException after
 * detached from the window.
 *
 * @author Eric Burke (eric@squareup.com)
 */
public class SafeViewFlipper extends ViewFlipper {
  public SafeViewFlipper(Context context) {
    super(context);
  }

  public SafeViewFlipper(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  /**
   * Workaround for Android Bug 6191:
   * http://code.google.com/p/android/issues/detail?id=6191
   * <p/>
   * ViewFlipper occasionally throws an IllegalArgumentException after
   * screen rotations.
   */
  @Override protected void onDetachedFromWindow() {
    try {
      super.onDetachedFromWindow();
    } catch (IllegalArgumentException e) {
      Log.d(TAG, "SafeViewFlipper ignoring IllegalArgumentException");

      // Call stopFlipping() in order to kick off updateRunning()
      stopFlipping();
    }
  }
}

您可以在从代码创建布局时使用它,也可以将其嵌入到您的 xml 布局文件中(您必须完全限定它,例如 <com.myapp.SafeViewFlipper/>).

You can use it while creating the layout from the code as well as embed it into your xml layout file (you'll have to qualify it fully, eg. <com.myapp.SafeViewFlipper />).

另请参阅 http://code.google.com/p/android/issues/detail?id=6191 了解更多信息.

See also http://code.google.com/p/android/issues/detail?id=6191 for more informations.