我想在单击按钮后从活动切换到片段。单击按钮时应用程序崩溃并给出此错误
对于过渡,我写了它
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.notesFragment,new NotesFragment());
fragmentTransaction.commit();
}
});
fragment_notes.xml
我给id作为"noteFragment">
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Fragments.NotesFragment"
android:background="@color/mainDarkBlue"
android:id="@+id/notesFragment">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
app:fabSize="auto"
android:layout_margin="@dimen/fab_margin"
android:backgroundTint="@color/rossyBrown"
android:src="@drawable/ic_fab_add_note"
android:id="@+id/button_fab"/>
...
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</FrameLayout>
您需要传递父类 ID 来膨胀片段,而不是片段名称本身
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.parentLayoutId, new NotesFragment());
//Change R.id.notesFragment to your parent class main layout id
fragmentTransaction.commit();
}
});
类似的东西
<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">
<Button
android:id="@+id/BtnRedirectFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Default Fragment" />
<!-- Frame Layout for placing Fragments -->
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>