Прерывание анимированной навигации на Android приводит к пустому экрану

#android #animation #navigation #transition #androidx

#Android #Анимация #навигация #переход #androidx

Вопрос:

У меня проблемы с анимацией между фрагментами. При быстром нажатии кнопки «Назад» во время перехода фрагмента я могу достичь состояния, при котором NavHostFragment внутренняя часть макета действия кажется пустой.

Вот видео, которое демонстрирует проблему:

введите описание изображения здесь

Как вы можете видеть на видео, нажатие кнопки «Назад» после завершения перехода приводит ко второму фрагменту, как и ожидалось. Однако, когда анимация все еще выполняется, иногда нажатие кнопки «Назад» очищает целое NavHostFragment , и мне представляется пустое представление.

Чем длиннее анимация, тем больше вероятность того, что я получу пустой экран. Возможно, я неправильно применяю анимацию, поэтому ниже приведен весь соответствующий код для этого примера.

MainActivity :

 public class MainActivity extends androidx.appcompat.app.AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_test);
    }
}
 

FirstFragment :

 public class FirstFragment extends androidx.fragment.app.Fragment {

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        view.findViewById(R.id.to_second_fragment).setOnClickListener(v -> androidx.navigation.Navigation.findNavController(view).navigate(R.id.action_first_fragment_to_second_fragment));
    }
}
 

activity_navigation_test :

 <?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@ id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigation_test" />

</androidx.constraintlayout.widget.ConstraintLayout>
 

navigation_test :

 <?xml version="1.0" encoding="utf-8"?>
<navigation
    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:id="@ id/navigation_test"
    app:startDestination="@id/first_fragment">

    <fragment
        android:id="@ id/first_fragment"
        android:name="com.test.navigation.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@ id/action_first_fragment_to_second_fragment"
            app:destination="@id/second_fragment"
            app:enterAnim="@anim/slide_in_from_right"
            app:exitAnim="@anim/slide_a_little_out_to_left" />
    </fragment>

    <fragment
        android:id="@ id/second_fragment"
        android:name="com.test.navigation.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" />
</navigation>
 

slide_in_from_right ( slide_a_little_out_to_left то же самое, за исключением значений fromX и toX):

 <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="666"
    android:shareInterpolator="false">

    <translate android:fromXDelta="100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator" />
</set>
 

Я использую следующие версии библиотеки:

 androidx.appcompat:appcompat:1.3.0-alpha02
androidx.fragment:fragment:1.2.5
androidx.navigation:navigation-fragment:2.3.1
androidx.navigation:navigation-ui:2.3.1
 

Комментарии:

1. appcompat:1.3.0-alpha02 зависит от более старой версии Fragments (1.3.0-alpha08), которая переопределяет вашу fragment:1.2.5 зависимость. Вы видите ту же проблему при обновлении до последней версии Fragment 1.3.0-beta02?

2. Я действительно использовал версию 1.3.0-beta01 в реальном проекте, но проблема была все та же. В любом случае, обновление до 1.3.0-beta02 сделало свое дело, большое вам спасибо! В примечаниях к изменениям действительно упоминается об этом; рад, что это было исправлено, мы скоро выпустим. Вы можете опубликовать это в качестве ответа здесь, если вам нужен представитель 🙂