Fragment not attached to a context

前端 未结 7 1248
鱼传尺愫
鱼传尺愫 2020-12-14 14:58

In activity in Toolbar I got a button which need to call method from fragment and update list in that fragment. Now it is an error. Calling in activity

@Over         


        
7条回答
  •  死守一世寂寞
    2020-12-14 15:30

    Create a fragment instance is not enough.
    It needs to be attached to Activity through a transaction:

    getFragmentManager()
        .beginTransaction()
        .replace(R.id.container_layout, fragment)
        .commit();
    

    After a successful commit, onAttach method in the fragment is called, the view is created and then you can interact with its views.

    In your case, create the fragment instance and attach it in activity onCreate, then call sortByPopularity later in a click event.

    Read more about fragment life cycle: https://developer.android.com/guide/components/fragments

提交回复
热议问题