Home » Android » java – onCreateView Fragment not called

java – onCreateView Fragment not called

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a custom DialogFragment with a FrameLayout container in which I want to put a Fragment but its view always return null, what can I do?

In DialogCreateAccount.java

   public class DialogCreateAccount extends DialogGeneral implements OnClickListener{

   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    Dialog dialog = super.onCreateDialog(savedInstanceState);

    //........


    return dialog;

   }


@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

     Fragment fragment = CreateAccountFragment.newInstance();


     FragmentTransaction ft = getFragmentManager().beginTransaction();

         if(fragment.getView()!=null){ // return always null

            ft.add(
                    getFrameContainer().getId(),
                    fragment
                    )
            .commit();
         }else{

         }

        Log.i("DialogCreateAccount", "fragment:" +fragment.getView());// return null
  }

In CreateAccountFragment.java

 public class CreateAccountFragment extends Fragment implements OnClickListener{

        public CreateAccountFragment() {
          // TODO Auto-generated constructor stub

        }

       public static CreateAccountFragment newInstance() {

             CreateAccountFragment f = new CreateAccountFragment();

             return f;
       }

       @Override
       public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
         super.onCreate(savedInstanceState);
         Log.i("CreateAccountFragment", "onCreate");
         //onCreate is called


       }

       @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
          // TODO Auto-generated method stub

      Log.i("CreateAccountFragment", "onCreateView");
        //onCreateView not called

          mRootView = inflater.inflate(R.layout.dialog_create_an_account, container, false);




          return mRootView;


       }
      }

In Fragment onCreate is called and onCreateView is not called.

How to&Answers:

Fragment getView() only returns a non-null view once onCreateView() has been run in the fragment lifecycle.

Merely instantiating a fragment object does not call any of its lifecycle callbacks. They will be called later when the fragment transaction executes.

Just put the fragment in the container without conditionally checking whether getView() returns non-null.

Answer:

Your fragment has to be associated with a view. This can be done either be done in xml layout or programmatically.

See Fragments documentation, section “Adding fragment to an activity”.