将片段添加到对话框中

时间:2013-08-18 10:17:24

标签: android android-fragments android-dialogfragment android-nested-fragment

我想在对话框中添加一个片段(它可以是DialogFragment或常规Dialog)。我该怎么做?

这是我的DialogFragment:

public class MyDialogFragment extends DialogFragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MyDialogFragment2 dialog = new MyDialogFragment2();
        View v = inflater.inflate(R.layout.news_articles, container, false);
        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, dialog).commit();
        return v;
    }

}

这是news_article.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是我的主要活动:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            MyDialogFragment dialog = new MyDialogFragment();
            dialog.show(getSupportFragmentManager(), "asdf");
        }
    });
}

但是当我尝试它时,我得到了:

No view found for id 0x7f070002 for fragment MyDialogFragment2

我认为这是因为Activity的FragmentManager不是我应该添加的那个,但我找不到DialogFragment的那个,它在哪里?

2 个答案:

答案 0 :(得分:10)

答案(感谢@Luksprog)使用getChildFragmentManager而不是getActivity()。getSupportFragmentManager

它不适合我,因为我必须升级我的support-v4 jar,如下所述:android.support.v4.app.Fragment: undefined method getChildFragmentManager()

答案 1 :(得分:10)

Dialog的布局 - R.layout.view_with_plus

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.util.me.TestActivity"
    >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Details"/>
    <fragment
        android:layout_toRightOf="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/email"
        class="com.util.me.test.PlusOneFragment"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

如何显示对话框

public void showDialog(View vIew){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    View view = this.getLayoutInflater().inflate(R.layout.view_with_plus, null);
    builder.setView(view)
            .setPositiveButton("OK", null)
            .setNegativeButton("Cancel", null);

    AlertDialog dialog = builder.create();
    dialog.show();
}

class =“com.util.me.test.PlusOneFragment”中的片段只是Android Studio生成的PlusOneFragment。