向对话框添加片段 [英] Adding a fragment to a dialog

查看:101
本文介绍了向对话框添加片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add a fragment to a dialog (it can be either a DialogFragment or a regular Dialog). How do I do that?

这是我的DialogFragment:

Here's my 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:

Here's 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");
        }
    });
}

但是当我尝试时,我会得到:

But when I try it I get:

No view found for id 0x7f070002 for fragment MyDialogFragment2


$ b $的ID 0x7f070002的视图b

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

I think it's because the FragmentManager of the Activity isn't the one I should be adding to, but I can't find the one of the DialogFragment, where is it?

推荐答案

答案(由于@Luksprog)正在使用getChildFragmentManager而不是getActivity()。getSupportFragmentManager

The answer (thanks to @Luksprog) is using the getChildFragmentManager instead of getActivity().getSupportFragmentManager

它对我不可用,因为我不得不升级我的support-v4 jar,如下所述: android.support.v4.app.Fragment:未定义的方法getChildFragmentManager()

It wasn't available for me, cause I had to upgrade my support-v4 jar, as described here: android.support.v4.app.Fragment: undefined method getChildFragmentManager()

这篇关于向对话框添加片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆