问题
I have a lifecycle aware fragment and a LifecycleObserver
class
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyObserver(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
}
Following is my Observer class where it logs all the fragment events propery
public class MyObserver implements LifecycleObserver {
private static final String TAG = "MyObserver";
public MyObserver(LifecycleOwner lifecycleOwner) {
lifecycleOwner.getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(){
Log.d(TAG, "onCreate: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){
Log.d(TAG, "onPause: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(){
Log.d(TAG, "onDestroy: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(){
Log.d(TAG, "onStart: ");
}
}
I want to listen to fragment specific lifecycle events like onDestroyView
and onActivityCreated
but these events are not there in
Lifecycle.Event
. It contains only activity events. How can I listen for fragment events in my observer
回答1:
You can observe the fragment's viewLifecycleOwner
lifecycle.
viewLifecycleOwner.lifecycle.addObserver(yourObserverHere)
Then the fragment's onDestroyView
lifecyle method is tied to the @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
annotated method.
Note that the fragment's viewLifecycleOwner
is only available between onCreateView
and onDestroyView
lifecycle methods.
回答2:
Just a supplement to Basim Alamuddin's answer:
As you can see in the resource codes, @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
is also called when you add an observer to viewLifecycleOwner
: viewLifecycleOwner.lifecycle.addObserver(this)
// androidx.fragment.app.Fragment
void performDestroyView() {
if (mView != null) {
mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
onDestroyView();
void performDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
onDestroy();
回答3:
Well, according to this, literally onDestroyView
will be called after onStop
. So, If you need the logic to run before onDestroyView or detecting it, i think it's is best to call it or detect in the fragment's onStop() method. In your case, i think you need to implement Lifecycle.Event.ON_STOP
& Lifecycle.Event.ON_START
for onActivityCreated
.
Hope it helps you.
回答4:
Fragment Life Cycle
onCreateView()
Called to create the view hierarchy associated with the fragment.
onDestroyView()
Called when the view hierarchy associated with the fragment is being removed.
来源:https://stackoverflow.com/questions/47091794/fragment-lifecycle-events-in-lifecycleaware-fragment