在重新加载或旋转后刷新片段

时间:2016-01-24 07:42:35

标签: android

我在旋转屏幕时写下了以下代码片段重新生成。

片段setArguments发生“java.lang.IllegalStateException”错误。

有什么更好的方法可以做?

参考:retain the fragment object while rotating

参考:refresh fragment at reload

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String tag = "my_fragment";
    FragmentManager fragmentManager = getFragmentManager();
    Fragment f = fragmentManager.findFragmentByTag(tag)
    if(f == null) { //or if(null == savedInstanceState){
        //create Fragment
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        Fragment homeFragment = new Home();
        fragmentTransaction.add(R.id.mainFragement, homeFragment, tag);
        fragmentTransaction.commit();
    } else {
        //renew Fragment
        Bundle newArgs = //want to renew Args
        f.setArguments(newArgs);

        ft.detach(f);
        ft.attach(f);
        ft.commit();
    }
}

01-24 16:00:54.905: E/VideoPlayerActivity.java # onNewIntent:319(22727): Fragment already active
01-24 16:00:54.905: E/VideoPlayerActivity.java # onNewIntent:319(22727): java.lang.IllegalStateException: Fragment already active
01-24 16:00:54.905: E/VideoPlayerActivity.java # onNewIntent:319(22727):    at android.support.v4.app.Fragment.setArguments(Fragment.java:551)

1 个答案:

答案 0 :(得分:0)

对不起。
我自己解决了,谢谢你。

} else {
    //renew Fragment
    f.getArguments().putInt(XXXXXXX, x);
    f.getArguments().putSerializable(XXXXXXX, X);

    FragmentTransaction ft = fragmentManager().beginTransaction();
    ft.detach(f);
    ft.attach(f);
    ft.commit();
}