我有一个使用自定义布局的对话框片段,其中包含非常复杂的View层次结构。对话框片段的代码或多或少类似于以下内容。
public class CardDetailDialog extends DialogFragment {
public CardDetailDialog() {
setRetainInstance(true);
setStyle(STYLE_NORMAL, android.R.style.Theme_Light);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_detail_dialog, container, false);
/* Modify some view objects ... */
return view;
}
}
每当我为此对话框片段调用show()
方法时,我注意到始终调用onCreateView
并重复布局膨胀过程。在我的应用程序中,用户可能希望在会话期间多次显示该对话框,我认为这是低效的。有没有办法在多个show()
调用中保持视图/对话框实例?是否可以使用DialogFragment执行此操作,还是必须直接处理Dialog
类?
答案 0 :(得分:1)
使用布尔标志似乎可以解决问题(参见KEY CHANGE)。我重写onCreateDialog,但在onCreateView中使用相同的策略也应该可以工作(保持对你创建的视图的引用)
我仍然遇到一些与方向更改有关的问题,但可能与a different issue
有关public class LogFragment extends DialogFragment{
private boolean isCreated; //KEY CHANGE
private Dialog mDialog; //KEY CHANGE -- to hold onto dialog instance across show()s
public LogFragment() {
setRetainInstance(true); // This keeps the fields across activity lifecycle
isCreated = false; // KEY CHANGE - we create the dialog/view the 1st time
}
@Override
public Dialog onCreateDialog(Bundle inState) {
if (isCreated) return mDialog; // KEY CHANGE - don't recreate, just send it back
View v = View.inflate(getActivity(),R.layout.log_layout,null);
mDialog = new AlertDialog.Builder(getActivity())
...
.create();
isCreated = true; // KEY CHANGE Set the FLAG
return mDialog;
}