Android Fragment分离

时间:2014-10-06 12:28:08

标签: android android-fragments android-fragmentactivity detach

我有两个片段的活动。一个片段以纵向显示,另一个以横向模式显示。片段随java一起添加。

Fragment fragment = null;
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            fragment = new FragmentPortrait();
        } else {
            fragment = new FragmentLandscape();
        }

        if (fragment != null) {
            addFragment(fragment, savedInstanceState == null);
        }

private void addFragment(Fragment fragment, boolean add) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();

        detachFragment("fragment");

        if (add) {
            fragmentTransaction.add(R.id.layoutForFragment, fragment,
                    "fragment");
        } else {
            fragmentTransaction.replace(R.id.layoutForFragment,
                    fragment, "fragment");
        }

        fragmentTransaction.commit();
    }

private void detachFragment(String fragmentTag) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                fragmentTag);

        if (fragment != null) {
            Log.i(TAG, "detaching");
            getSupportFragmentManager().beginTransaction().remove(fragment)
                    .commit();
        }
    }

我的问题是,如果我在纵向模式下开始活动,当我旋转屏幕时,景观片段会按预期显示,但也会调用纵向片段中的onActivityCreated。这意味着肖像片段仍然存在。你能告诉我我的错误在哪里吗?

1 个答案:

答案 0 :(得分:0)

Keep it simple :: Replacing Fragment = Removing Current Fragment + Adding New Fragment


Sample :: 使用saveInstance和其他内容修改您的需求


Boolean mFlag=false;
{
        Fragment fragment = null; 

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        if(mFlag==false) 
            FragmentPortrait();
            mFlag=true; 
        } else { 
        if(mFlag==true)
            FragmentLandscape();
            mFlag=false;
        } 

        FragmentPortrait(){
         // Perform Action:: Replacing a fragment with the fragment you want to add in Portrait
        }

        FragmentLandscape(){
        // Perform Action:: Replacing a fragment with the fragment you want to add in Landscape
        }

}