在Android中无需重新加载片段即可处理按下返回按钮



我正试图按下后退按钮并返回到前一个片段,而不是每次都加载整个片段。我看了stackoverflow,但还没找到答案。目前,当我切换片段时,不同的片段会重叠,即使后退按钮按预期工作。

主要活动.java

getSupportFragmentManager().beginTransaction().add(R.id.frag_container, new CatalogueFragment()).addToBackStack(null).commit();

也在MainActivity.java中

@Override
public void onBackPressed()
{
if(getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
super.onBackPressed();
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
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">
<data>
<variable
name="genericViewModel"
type="MainActivity"/>
</data>
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start"
>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#000"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/favourites_recycler"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:padding="4dp"
/>
<FrameLayout
android:id="@+id/frag_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/side_navbar"
app:itemTextColor="@color/black"
app:itemIconTint="@color/black"/>
</androidx.drawerlayout.widget.DrawerLayout>
</layout>

有两种方法可以修复它。

  1. 您可以设置CatalogueFragment视图的背景,我指的是当您在CatalogueFragment中调用onCreateView时ViewGroup的背景

  2. 在调用addFragment之前,您应该通过标记获取当前Fragment,并使Fragment事务隐藏它

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (!fragments.isEmpty()) {
for (Fragment fragment : fragments) {
if (!fragment.isHidden()) {
transaction.hide(fragment);
}
}
}

最新更新