Android DialogFragment: how to keep view across multiple show () calls?

I have a snippet of a dialog using a custom layout with a rather complex View hierarchy. The dialogue fragment code is more or less similar to the following.

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;
    }
}

      

Whenever I called a method show()

for this piece of dialog, I noticed that it was onCreateView

always called and the layout inflation process was repeated. In my application, the user can display the dialog multiple times during the session and I thought it was inefficient. Is there a way to keep an instance of the view / dialog across multiple calls show()

? Can this be done with DialogFragment, or do I need to deal directly with the class Dialog

?

+3


source to share


1 answer


Using boolean flag seems to do the trick (see KEY CHANGES). I am overriding onCreateDialog but using the same strategy in onCreateView should work as well (keep a reference to the created view)

I am still having some problems with orientation changes, but it might be related to another problem



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;
}

      

+1


source







All Articles