FragmentManager.findFragmentByTag()的奇怪行为

时间:2014-02-26 09:22:26

标签: android android-fragments

好的,今天我注意到findFragmentByTag()的一个奇怪的行为:如果我旋转屏幕一次正确返回片段,但在第二次旋转时我总是得到null。难道我做错了什么?有没有办法来解决这个问题?

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        FragmentManager fm = getSupportFragmentManager();
        Fragment f = fm.findFragmentByTag("frag");
        if (f == null){
            Log.e("Fragment","null");
            f = new Fragment();
        }
        f.setRetainInstance(true);
        fm.beginTransaction().remove(f).add(f, "frag").commit();

    }

1 个答案:

答案 0 :(得分:3)

尝试在片段setRetainInstance(true);中调用onCreate()并将上面的代码更改为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstance == null){
        FragmentManager fm = getSupportFragmentManager();
        Fragment f = new Fragment();
        fm.beginTransaction().add(f, "frag").commit();
    }
}

同时设置ID以在布局视图组中显示它