4

我有一个对话框片段,它使用具有非常复杂的视图层次结构的自定义布局。对话框片段的代码或多或少类似于以下内容。

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类?

4

1 回答 1

1

使用布尔标志似乎可以解决问题(请参阅 KEY CHANGEs)。我重写了 onCreateDialog,但在 onCreateView 中采用相同的策略也应该可以工作(保留对您创建的视图的引用)

我仍然遇到一些与方向更改相关的问题,但可能与其他问题有关

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;
}
于 2013-09-28T09:14:26.930 回答