Проблема с транзакцией фрагмента
Как выглядит приложение : По одной из выборочных вариантов меню пользователь переходит на первый либо второй фрагмент. Приложение падает, я поняла так что причина в том что он не может найти контейнер. На месте R.id.fragmentContainer должен стоять ID контейнера фрагмента, но я без понятия где его объявить или искать. Вот моя функция по смене фрагментов
private fun changeFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction().replace(R.id.fragmentContainer, fragment)
.addToBackStack(fragment.javaClass.name).commit()
}
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
В родительской активности нужно добавить FrameLayout:
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
и по логике все должно заработать правильно, общий вид:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".TestActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Фрагмент 1" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Фрагмент 2" />
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Фрагмент 3" />
</LinearLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
плюс можно перенести fragmentManager переменную сразу в транзакцию если вы ее нигде больше не используете. Доп инфа