我有一个生命周期识别片段和一个LifecycleObserver
类
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);
}
}
以下是我的Observer类,它记录了所有片段事件
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: ");
}
}
我想听取片段特定的生命周期事件,例如onDestroyView
和onActivityCreated
,但这些事件不存在于
Lifecycle.Event
。它仅包含活动事件。我如何在观察者中监听片段事件
答案 0 :(得分:1)
您可以观察片段的multi_array list is:
[[40, 107, 23, 27, 42], [150, 84, 108, 191, 172], [154, 22, 161, 26, 31], [18, 150, 197, 77, 191], [96, 124, 81, 1
25, 186]]
sorted 2D array:
[[18, 22, 23, 26, 27], [31, 40, 42, 77, 81], [84, 96, 107, 108, 124], [125, 150, 150, 154, 161], [172, 186, 191, 1
91, 197]]
Not Found
生命周期。
viewLifecycleOwner
然后将片段的viewLifecycleOwner.lifecycle.addObserver(yourObserverHere)
生命周期方法与带有注释的onDestroyView
方法联系起来。
请注意,片段的@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
仅在viewLifecycleOwner
和onCreateView
生命周期方法之间可用。
答案 1 :(得分:0)
只是Basim Alamuddin的回答的补充:
如您在资源代码中所见,将观察者添加到@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
时,也会调用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();
答案 2 :(得分:-2)
答案 3 :(得分:-2)
嗯,根据this,字面onDestroyView
将在onStop
之后调用。因此,如果您需要在onDestroyView之前运行逻辑或检测它,我认为最好在片段的onStop()方法中调用它或检测它。在您的情况下,我认为您需要实施Lifecycle.Event.ON_STOP
& Lifecycle.Event.ON_START
的{{1}}。
希望它对你有所帮助。