问题
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?
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;
}
}
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" />
Here's my main activity:
@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
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?
回答1:
The answer (thanks to @Luksprog) is using the getChildFragmentManager instead of getActivity().getSupportFragmentManager
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()
回答2:
Layout for 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>
How to show the Dialog
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();
}
The fragment in class="com.util.me.test.PlusOneFragment" is just a PlusOneFragment generated by Android Studio.
来源:https://stackoverflow.com/questions/18298052/adding-a-fragment-to-a-dialog