Android SettingsActivity已泄露窗口

时间:2014-08-26 15:13:48

标签: android android-fragments

我有一个简单的SettingsActivity,它包含一个首选项片段。此片段显示一个用于打开列表对话框的按钮。通过提供preferences.xml文件自动创建视图和对话框。

public class SettingsActivity extends FragmentActivity {

    private static final String TAG_SETTINGS_FRAGMENT = "settings_fragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new SettingsFragment(), TAG_SETTINGS_FRAGMENT).commit();
        }
    }

    public static class SettingsFragment extends PreferenceFragment{

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // init settings here
            setRetainInstance(true);
        }
    }
}

所以一切正常,除非我在对话框出现时旋转屏幕。在旋转时,对话框消失。当我再次展示它时,我得到以下异常:

  

E / WindowManager:android.view.WindowLeaked:Activity SettingsActivity   已经泄露了窗户   com.android.internal.policy.impl.PhoneWindow $ {DecorView 42300a98   最初添加的V.E ..... R ....... 0,0-729,1134}               在android.view.ViewRootImpl。(ViewRootImpl.java:346)               在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)               在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)               在android.app.Dialog.show(Dialog.java:286)               在android.preference.DialogPreference.showDialog(DialogPreference.java:308)               在android.preference.DialogPreference.onClick(DialogPreference.java:266)               在android.preference.Preference.performClick(Preference.java:952)               在android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:215)

在此之后,我通过向后移动并立即获得此异常来销毁活动:

  

java.lang.RuntimeException:无法销毁活动   {SettingsActivity}:java.lang.IllegalArgumentException:   查看= com.android.internal.policy.impl.PhoneWindow $ {DecorView 423fc108   V.E ..... R ....... 0,0-729,1134}未附加到窗口管理器

任何想法如何避免这种情况?

2 个答案:

答案 0 :(得分:1)

尝试删除setRetainInstance(true)

我有同样的问题,当我停止保留片段时,它就消失了。

答案 1 :(得分:0)

为什么不在不检查savedInstance的情况下创建片段?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment(), TAG_SETTINGS_FRAGMENT).commit();
}