Is it possible to access fragment's UI elements from activitiy's onCreate

前端 未结 3 1500
借酒劲吻你
借酒劲吻你 2021-01-29 06:37

As the headline says: Is it possible to get the currently visible fragment with all UI elements initialized within the onCreate() method of the activity? I am implementing a sep

相关标签:
3条回答
  • 2021-01-29 07:10

    By default, no. At the time activity onCreate() runs, the fragment is not attached to the activity yet.

    Right place to access a fragment's views is in the fragment itself. Consider putting the controller assignments in the fragment within its lifecycle such as onCreateView() or onViewCreated().

    It is possible to explicitly run queued up fragment transactions using executePendingTransactions(), or implicitly after super.onStart() has been run in the activity lifecycle. After that the fragment views are accessible in the activity view hierarchy.

    0 讨论(0)
  • 2021-01-29 07:13

    in your onCreate method add the following (I used a textview as an example):

    while (fragment.getView() == null) {
    
            }
    rootView = fragment.getView();
    TextView myView = (TextView) rootView.findViewById(R.id.text_view);
    

    Make sure to return the rootView in your fragment's onCreateView method as follows:

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_activity,
                    container, false);
            return rootView;
        }
    

    I know that the idea of getting your fragment to access its views from the main activity is bad. Yet, this solution may give you what you want.

    0 讨论(0)
  • 2021-01-29 07:18

    YOu can create an Interface in activity and implement it on Fragment...

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