Добавление фрагмента в диалог
Я хотел бы добавить фрагмент в диалог (это может быть либо диалоговое окно 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
Я думаю, потому что FragmentManager Activity не является тем, к которому я должен добавить, но я не могу найти один из DialogFragment, где он?
Ответы
Ответ 1
Ответ (спасибо @Luksprog) использует getChildFragmentManager вместо getActivity(). getSupportFragmentManager
Он не был доступен для меня, потому что мне пришлось обновить банку поддержки-v4, как описано здесь: android.support.v4.app.Fragment: undefined method getChildFragmentManager()
Ответ 2
Макет для диалога - 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" - это просто фрагмент PlusOneFragment, созданный Android Studio.