在活动布局中重用DialogFragment作为片段

时间:2014-03-06 17:03:14

标签: android android-fragments android-dialogfragment

尝试在活动布局中将复杂的DialogFragment重用为片段。我不想重写这整个DialogFragment类,因为它非常复杂。在一个地方,设计师只希望这种布局不是作为弹出窗口而是在页面中。有没有办法绕过DialogFragment抛出这个(来自DialogFragment.java):

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

我甚至在OnCreateDialog()重写方法中忽略了Dialog的创建,并添加了重写方法onCreateView()。但仍然视图不为null并抛出IllegalStateException。我将片段嵌入活动布局

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

所以问题是,无论如何在Activity的布局中重新使用DialogFragment作为片段?

1 个答案:

答案 0 :(得分:1)

你不能将DialogFragment用作常规片段吗?

像这样:

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