onCreateView() of nested fragment is not called

前端 未结 2 520
眼角桃花
眼角桃花 2020-12-06 23:31

I have been going through nested fragments documentation, best practices and all possible links here in StackOverflow. I have seen suggestions to avoid using fragment tag i

相关标签:
2条回答
  • 2020-12-06 23:39

    Don't call the transactions inside of onCreateView either use onActivityCteated or onCreate.

    Also worth noting don't call, executePendingTransactions when you are inside a of the parent fragment, that is bound to break something.

    Try to setup your parent fragment something like this:

    public class MessageFragment extends Fragment {
      private EditText msgText;
    
      private Activity activity;
    
      TextView tvTitle, tvContent, tvIntro;
      Button bAction;
    
      public static MessageFragment newInstance() {
        MessageFragment f = new MessageFragment();
        return (f);
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.message, container, false);
        tvTitle = (TextView) view.findViewById(R.id.fragment_title);
        tvIntro = (TextView) view.findViewById(R.id.fragment_intro);
        tvContent = (TextView) view.findViewById(R.id.fragment_contents);
        bAction = (Button) view.findViewById(R.id.fragment_action);
        return view;
      }
    
      @Override
      public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = getActivity();
        if (activity != null) {
            Fragment fragment = getChildFragmentManager().findFragmentById(R.id.sms_message);
            Log.d("MESSAGE_FRAGMENT", "onActivityCreated" + fragment);
            msgText = (EditText) ((MessageEditFragment)fragment).getView().findViewById(R.id.message_edit_text);
            bAction.setEnabled(!msgText.getText().toString().trim().equals(""));
            msgText.selectAll();
        }
        Fragment fragment = MessageEditFragment.newInstance();
        getChildFragmentManager().beginTransaction()
          .replace(R.id.sms_message, fragment)
          .commit();
      }
    }
    
    0 讨论(0)
  • 2020-12-06 23:43

    Maybe you should not add child fragment(say call transaction.add within a fragment).

    Do fragment transaction only on Activity.

    When you want to do fragment transaction, you could notify the Activity hosting the current fragment, through EventBus, or an interface implemented by the host Activity.

    0 讨论(0)
提交回复
热议问题