onResume()我在擴展的自定義片段中有以下代碼ListFragment,它試圖找到它的父:
@Override
public void onResume() {
super.onResume();
System.out.println("resume");
View view = getView();
System.out.println("view is " (view != null ? "not " : "" ) "null");
ViewParent parent = view != null ? view.getParent() : null;
System.out.println("parent is " (parent != null ? "not " : "" ) "null");
if(view != null) {
System.out.println(view.getRootView());
}
}
當我最初在模擬器中運行應用程式時,它會列印:
I/System.out: resume
I/System.out: view is not null
I/System.out: parent is not null
I/System.out: com.android.internal.policy.impl.PhoneWindow$DecorView{ ... }
但是,在旋轉模擬器后,它會列印:
I/System.out: resume
I/System.out: view is not null
I/System.out: parent is null
I/System.out: android.widget.FrameLayout{ ... }
即使片段在應用程式中可見,它看起來好像它的視圖onResume()在旋轉后還沒有正確附加到視圖樹中,因為根視圖是FrameLayout片段的根視圖而不是根視圖的應用程式。
這可能是什么原因,我怎樣才能正確地訪問它的ViewParentin/after onResume(),而不訴諸于某事線getActivity().findViewById(someId)?
編輯:
當我調整代碼onResume()以在下一幀中列印根視圖時(使用View.post()),它確實找到了正確的根視圖(這意味著我可以訪問父視圖):
@Override
public void onResume() {
super.onResume();
System.out.println("resume");
View view = getView();
System.out.println("view is " (view != null ? "not " : "" ) "null");
ViewParent parent = view != null ? view.getParent() : null;
System.out.println("parent is " (parent != null ? "not " : "" ) "null");
if(view != null) {
System.out.println(view.getRootView());
/**
* added to see if it finds the proper root view in the next frame
*/
view.post(() -> {
System.out.println("how about after post?");
System.out.println(view.getRootView());
});
}
}
現在它列印:
I/System.out: view is not null
I/System.out: parent is null
I/System.out: android.widget.FrameLayout{ ... }
I/System.out: how about after post?
I/System.out: com.android.internal.policy.impl.PhoneWindow$DecorView{ ... }
但是View.post()像這樣使用感覺就像一個討厭的黑客。
編輯:
因此,操作順序似乎與我預期的不同(可能是錯誤?)。
但我可能已經找到了一個解決方案,如果它按預期作業,我將作為答案發布。這個想法是將 a 添加View.OnAttachStateChangeListener到片段視圖中onViewCreated(),從而找到父級 inView.OnAttachStateChangeListener.onViewAttachedToWindow()而不是 in Fragment.onResume()。
uj5u.com熱心網友回復:
我設法通過將我的邏輯從我添加的onResume()邏輯中解決了這個問題:View.OnAttachStateChangeListeneronViewCreated()
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
System.out.println(view.getParent());
}
@Override
public void onViewDetachedFromWindow(View view) {
view.removeOnAttachStateChangeListener(this);
}
};
}
現在它的行為符合我的預期。
要點在于onResume(),假設片段視圖已經附加到視圖樹,這不是一種可靠的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463057.html
