我正在使用片段事务在按下按钮时在组件之间切换。为了使整体体验更好,我添加了自定义动画,将旧片段从左侧动画化,将新片段从右侧动画化。
启动此事务的代码如下所示:
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left)
.replace(R.id.fragment_container, contentModel.contentFragment, CONTENT_FRAGMENT_TAG)
.commit()
对于 Enter_from_right.xml,我使用的动画如下所示:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="450">
<translate
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="500"/>
</set>
和 exit_to_left.xml:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="0"
android:toXDelta="-100%"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="500"/>
</set>
EDIT我要替换的片段如下所示:
<?xml version="1.0" encoding="utf-8"?>
<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:paddingTop=“20”
android:layout_margin=“10”
android:orientation="vertical">
<TextView
android:lineSpacingExtra=“7”
android:id="@+id/questionTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom=“10”
tools:text=“Question title text“/>
<LinearLayout
android:id="@+id/textInputContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Dynamically filled with TextInputLayout and TextInputEditText elements containing answers -->
</LinearLayout>
<FrameLayout
android:layout_marginTop=“10”
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="@+id/nextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text=“Next question” />
</FrameLayout>
</LinearLayout>
但是,如果我在片段事务忙于动画时暂停应用程序(按主页按钮)(因此在按钮单击和 +- 1 秒之间),然后返回视图,则会发生以下奇怪的行为:
我要替换的片段(因此应该在动画之后删除的片段)在屏幕上仍然可见,但我无法与它交互,并且它不会显示在 Android Studio 的布局检查器中的任何位置。
它也不会位于正常内容的后面,而是位于正常内容的前面(但点击会穿过它)。
唯一可行但我不想使用它的方法是将 addToBackStack 添加到事务中,因为我没有使用事务返回堆栈,然后我需要添加丑陋的代码来清除返回堆栈。
我想知道是否还有其他人遇到过这个问题并得到了好的解决方案。