开发者

Android Add Fragment Without Transaction

I'm trying to replace a Fragment with another Fragment dynamically in my activity.

It looks like you can't replace a fragment statically defined in a layout file, with a dynamically created fragment: Android: can't replace one fragment with another

The suggested solution was to add the original Fragment dynamically in the onCreate method:

public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ShelfFragment shelves = new ShelfFragment();
    ft.add(R.id.left_fragment, shelves);
    ft.addToBackStack(null);
    ft.commit();
    }

This works, but when the user presses the back button, the original Fragment is removed instead of closing the Activity because the FragmentTransaction added it to the FragmentManager stack.

Is there a way to add the initial Fragment to my开发者_开发百科 activity without a Transaction/Stack entry?


Don't add it the backstack. Delete the ft.addToBackStack(null); line, you only need this if you want to be able to go back to the previous state with the back button.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜