JPM
JPM

Reputation: 9306

Re-Use DialogFragment as a Fragment in Activity Layout

Was trying to reuse a complex DialogFragment as a Fragment in an activity layout. I don't want to have to re-write this whole DialogFragment class as it is quite complex. In one spot only does the designers want this layout not as a popup but in a page. Is there a way to get around the DialogFragment from throwing this (From DialogFragment.java):

    if (view != null) {
        if (view.getParent() != null) {
            throw new IllegalStateException("DialogFragment can not be attached to a container view");
        }
        mDialog.setContentView(view);
    }

I went so far as to null out the creation of Dialog in the OnCreateDialog() overridden method and added the overridden method onCreateView(). But still view is not null and throws the IllegalStateException. I have the fragment embedded in the activity layout

<fragment
     android:id="@+id/fragment_mine"
     android:name="com.test.MyDialogFragment"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:visibility="visible" />

So question is, is there anyway to re-use a DialogFragment as a Fragment in an Activity's layout?

Upvotes: 0

Views: 1567

Answers (1)

Dan Brough
Dan Brough

Reputation: 3025

Cant you just use your DialogFragment as a regular fragment ?.

Like so:

public class MainActivity extends FragmentActivity {

  @Override
  protected void onCreate(Bundle state) {
    super.onCreate(state);
    final int FRAGMENT_ID = 100;

    LinearLayout contentView = new LinearLayout(this);
    contentView.setOrientation(LinearLayout.VERTICAL);
    Button showButton = new Button(this);
    showButton.setText("Show Dialog");
    showButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        //using TestDialogFragment as a dialog
        new TestDialogFragment().show(getSupportFragmentManager(), "dialog");
      }
    });

    contentView.addView(showButton);

    final LinearLayout fragmentContainer = new LinearLayout(this);
    fragmentContainer.setId(FRAGMENT_ID);
    contentView.addView(fragmentContainer);

    setContentView(contentView);

    //using TestDialogFragment as a Fragment
    getSupportFragmentManager().beginTransaction()
        .replace(FRAGMENT_ID, new TestDialogFragment()).commit();

  }

  public static class TestDialogFragment extends DialogFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      TextView view = new TextView(getActivity());
      view.setText("Test Fragment");
      return view;
    }
  }
}

Upvotes: 1

Related Questions