我使用的Android兼容性库(V4版本8)。 在自定义DialogFragment的overrided方法onViewCreated没有得到called.For如。
public class MyDialogFragment extends DialogFragment{
private String mMessage;
public MyDialogFragment(String message) {
mMessage = message;
}
@Override
public Dialog onCreateDialog( Bundle savedInstanceState){
super.onCreateDialog(savedInstanceState);
Log.d("TAG", "onCreateDialog");
setRetainInstance(true);
//....do something
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.d("TAG", "onViewCreated");
//...do something
}
}
onViewCreated是没有得到记录。
那么,对于onViewCreated状态的文档“onCreateView(LayoutInflater,ViewGroup中,包)后立即调用返回”。
DialogFragment使用onCreateDialog而不是onCreateView,所以onViewCreated不会被解雇。 (将是我的工作原理,我还没有潜入android源码确认)。
从我的测试中, onViewCreated
不叫,如果onCreateView返回null,这是默认行为,所以如果你不使用onCreateView而手动调用setContentView
在onCreateDialog
,您可以手动调用onViewCreated
从onCreateDialog
:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog d = super.onCreateDialog(savedInstanceState);
d.setContentView(R.layout.my_dialog);
// ... do stuff....
onViewCreated(d.findViewById(R.id.dialog_content), savedInstanceState);
return d;
}
在这种情况下,确保在根元素my_dialog.xml
有android:id="@+id/dialog_content"
你可以看到什么是从源代码中发生的事情:
首先,由于不重写onCreateView()
的片段的观点将是无效的。 这可以从可见的源代码Fragment
-默认返回null
:
// android.support.v4.app.Fragment.java
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return null;
}
其次,因为你的观点是空的FragmentManager
不会叫onViewCreated()
从源代码FragmentManager
:
// android.support.v4.app.FragmentManager.java
if (f.mView != null) {
f.mInnerView = f.mView;
// ...
// only called if the fragments view is not null!
f.onViewCreated(f.mView, f.mSavedFragmentState);
} else {
f.mInnerView = null;
}
据美国商务部( 选择对话框或嵌入之间 ),并有它由我自己测试过,可以覆盖OnCreateView,用你的自定义布局膨胀并返回。 OnViewCreated将陆续推出
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.custom_layout, null);
//do whatever
return view;
}