Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add fragment with 0 containerViewId

Where does android add fragment when I call FragmentTransaction add (Fragment fragment, String tag)

I have written this code, but I can't see fragment's layout. It displays an empty screen.

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Fragment fragment = new TestFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(fragment, "test");
        ft.commit();
    } // onCreate

 public class TestFragment extends Fragment {

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup        container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.frag_layout, container, false);
        }
    } // TestFragment
like image 335
mallaudin Avatar asked Apr 07 '16 06:04

mallaudin


1 Answers

You need to specify layout resource ID so, the FragmentTransaction can add your fragment to that resource (container).

When you call FragmentTransaction.add(Fragment, Tag) you actually calling FragmentTransaction.add(0,Fragment,Tag) and keep in mind "0" is not a valid resource ID. So actually your fragment is created without any view.

It is possible to have fragments without the view so this method actually is used for those types of fragments which just created to do some processing but have no interactions with layouts

like image 199
Pooya Avatar answered Oct 18 '22 18:10

Pooya