开发者

Android Add Fragment Without Transaction

开发者 https://www.devze.com 2023-04-10 04:34 出处:网络
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 fragmen

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

精彩评论

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