【问题标题】:Android DialogFragment: How to preserve view in multiple show() invocation?Android DialogFragment:如何在多个 show() 调用中保留视图?
【发布时间】:2013-01-31 13:59:56
【问题描述】:

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

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

【问题讨论】:

    标签: android android-dialogfragment


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多