简体   繁体   中英

Make Fragment appear first in LinearLayout

I am building parts of my layout programmatically.

My process looks like this:

  • I inflate a layout: View view = inflater.inflate(R.layout.view_layout, viewGroup, false);
  • I add this view to the ViewGroup: viewGroup.addView(view);

Before adding views in this way, I first add a fragment to the root view of viewGroup :

  • getChildFragmentManager().beginTransaction().add(R.id.viewgroup_root, fragment, "fragment_tag").commit();

My ViewGroup is a LinearLayout and I am adding the Fragment before I add the other views. However, the Fragment is appearing last - after all the views I add using ViewGroup.addView() .

How can I get the added Fragment to be displayed first in the LinearLayout , and why is the LinearLayout displaying it last if it was added first?

commit() is asynchronous - it does not run immediately. Therefore you definitely are running your addView methods before your fragment is actually added.

As Fragments automatically are re-added to their respective layout based on ID and you do not control the ordering of when the fragment is added to the layout in those cases, you can't rely on any initial ordering.

Instead, you should always add a Fragment to its own container - if using Fragment 1.2.0 or higher (the latest right now is 1.2.5 ), you should add a FragmentContainerView to your LinearLayout . If you're using an earlier version of Fragments, you'd want to add a FrameLayout to your LinearLayout . In either case, you'd need to make sure you use setId() with that layout and use the same ID when you use add .

You will have to leave placeholder under your LinearLayout and use placeholder's ID to do beginTransaction/add stuff. Any viewgroup would do. You are not just adding another view to your viewgroup, you are adding a fragment. It has its own lifecycle, bound to entities hosting it (activity, fragment).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM