我正在尝试在DialogFragment的子类中添加一个片段。我有一个ID为pref_container
的FrameLayout,我想用一个名为settingsFragment
的片段替换。
问题是fragmentTransaction
找不到R.id.pref_container
,我不知道这是否是因为pref_container仅在onCreateView
中膨胀而不是活动的一部分? / p>
我对Android编程非常陌生,所以感谢您的宝贵时间。
class QuestionnaireDialog : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.questionnaire_layout,container,true)
val settingsFragment = ExercisesOnlySettingsFragment()
val ft = fragmentManager?.beginTransaction()
/// **** Here fragmentTransaction can't find R.id.pref_container because it's inflated later and not loaded as part of the activity? ****
ft?.add(R.id.pref_container, settingsFragment)
ft?.commit()
return view
}
}
我得到的运行时错误是
No view found for id 0x7f09009c (com.lescadeaux.kegel:id/pref_container) for fragment ExercisesOnlySettingsFragment{4ba4b89 #1 id=0x7f09009c}
这是我XML中与问卷调查表布局有关的部分
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/questionnaireLayout"
android:background="@android:color/background_light">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
app:layout_constraintTop_toBottomOf="@+id/textView5"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- RELAVENT PART -->
<FrameLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:id="@+id/pref_container">
</FrameLayout>
<!-- RELAVENT PART -->
</LinearLayout>
</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:2)
请尝试使用getChildFragmentManager()
(或等效的kotlin)代替您正在使用的getFragmentManager()
,它将起作用。