38

我试图在调用方法时加载新片段。此方法创建一个新片段并“替换”另一个片段:

private void showTestFragment(Fragment oldFragment, boolean addBackStack, BaseAdapter adapter, int position) {
    Cursor cursor = (Cursor)adapter.getItem(position);
    if(cursor != null){

        int idx = cursor.getColumnIndexOrThrow(Episode._ID);
        long rowId = cursor.getLong(idx);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if(oldFragment != null){
            Log.i(TAG, "Removing the old fragment");
            fragmentTransaction.remove(oldFragment);
        }

        TestFragment testFragment =  new TestFragment();
        testFragment.setId(rowId);

        fragmentTransaction.add(android.R.id.content, testFragment);

        if(addBackStack){
            Log.i(TAG, "Added to the backstack");
            fragmentTransaction.addToBackStack(TAG);
        }

        fragmentTransaction.commit();
        Fragment f = getFragmentManager()
                .findFragmentById(R.id.index);
        Log.i(TAG, "after commit, frag is "+ f);
    }
}

这工作正常,直到我回去。最后一个片段,当我回去时应该删除。在我要对活动实施方法之前

public void onBackPressed(){}

要删除最后一个片段,我想知道我是否正确处理了片段更改。看起来我在这里遗漏了一些东西..

4

3 回答 3

88

如果您真的想替换片段,请使用 replace() 方法,而不是执行 remove() 和 add()。

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(..............);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit(); 

不要忘记执行 addToBackStack(null) ,这样您之前的状态将被添加到 backstack 中,允许您使用后退按钮返回。

另请参阅https://developer.android.com/reference/android/app/FragmentTransaction.html#replace(int, android.app.Fragment, java.lang.String)

另一个很好的来源是http://developer.android.com/guide/components/fragments.html(搜索 replace() 函数)。

于 2013-01-16T16:09:51.193 回答
4

只需先删除并调用 super.onBackPressed

public void onBackPressed(){

    // here remove code for your last fragment
    super.onBackPressed();

}
于 2013-01-16T09:24:58.213 回答
0
//lets wait for systems back to finish

 super.onBackPressed();

//here we believe a fragment was popped, so we need to remove the fragment from ourbackstack
if(fragmentBackStack.size()>0)
{
    Log.d("custombackstack","before back: "+fragmentBackStack.size()+" current:"+fragmentBackStack.peek());

    fragmentBackStack.pop();            
}
//after popping is the size > 0, if so we set current fragment from the top of stack, otherwise we default to home fragment.
if(fragmentBackStack.size()>0)
{           
    Log.d("custombackstack","after back: "+fragmentBackStack.peek());
currentFragment = fragmentBackStack.peek();         
}
else
{           
    //back stack empty
    currentFragment = HOME_FRAGMENT;
}
于 2014-03-12T06:23:30.093 回答