使用事务,我尝试更改“活动”中的一个片段,但是上一个片段保持原样,新的片段覆盖了它:
这就是我更改片段的方式:
WorkoutDetailFragment details = new WorkoutDetailFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
details.setWorkout(id);
ft.replace(R.id.stopwatch_container, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
我该如何预防?
UPD:这是acivity_main.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:orientation="horizontal"
android:padding="16dp"
tools:context=".StopwatchFragment" >
<fragment
android:id="@+id/fragment2"
android:name="com.example.workout.WorkoutListFragment"
android:layout_width="160dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="@+id/stopwatch_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="@+id/fragment2"
app:layout_constraintTop_toTopOf="parent">
<fragment
android:id="@+id/fragment3"
android:name="com.example.workout.WorkoutDetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
UPD2:我找到了解决方案。我只是将片段视图嵌套在框架布局中。相反,使用片段事务后,我将片段直接添加到代码的框架布局中。
片段术语如何工作:
getSupportFragmentManager()
可以从Activity
活动引用或仅使用活动引用(例如requireActivity().getSupportFragmentManager()
getChildFragmentManager()
如果您位于Activity
:您不能直接从活动中调用此方法,甚至不能使用requireActivity()
如果您位于Fragment
:您可以调用此方法,因为它要求您处于碎片状态。当您在第一个片段中时,现在它将成为父片段。现在,父片段可以有子片段,但活动不能有子片段。这些通常在使用ViewPagers或嵌套ViewPager或嵌套片段中可见。
我认为我们不必写getParentFragmentManager()
。
然后让我从活动容器开始。
activity_main
<FrameLayout
android:id="@+id/stopwatch_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
主要活动
如果需要,请添加转换或后退堆栈。
我打电话getSupportFragmentManager()
是因为我们正在活动中。如果在片段内调用,则有所不同。
WorkoutDetailFragment fragment = new WorkoutDetailFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.stopwatch_container, fragment);
transaction.commit();
现在你正试图从另一个调用片段WorkoutDetailFragment
。让我们调用HomeFragment
HomeFragment fragment = new HomeFragment.newInstance();
FragmentManager manager = requireActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.stopwatch_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
要从现有片段中调用片段,请引用父活动requireActivity()
并对其进行调用getSupportFragmentManager()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句