onCreateView Fragment未调用

时间:2014-08-22 10:16:04

标签: java android android-fragments android-dialogfragment

我有一个自定义DialogFragment,其中包含FrameLayout容器,我想在其中放置Fragment,但其视图始终返回null,我该怎么办?

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
  }

在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;


       }
      }

在片段中onCreate被调用,onCreateView未被调用。

2 个答案:

答案 0 :(得分:8)

片段getView()仅在片段生命周期中运行onCreateView()后才返回非空视图。

仅仅实例化片段对象不会调用其任何生命周期回调。它们将在片段事务执行后稍后调用。

只需将片段放入容器中,无需有条件地检查getView()是否返回非空。

答案 1 :(得分:4)

您的片段必须与视图相关联。这可以通过xml布局或以编程方式完成。

请参阅Fragments documentation,“将片段添加到活动”部分。