Как я могу поместить контейнер, содержащий фрагмент, внутри ViewPager для анимации с эффектом флип-карты
У меня есть ViewPager с фрагментами. Каждый фрагмент состоит из ImageView с лицевой стороной "карты". Смахивание показывает следующую (или предыдущую) карту. Нажатие на кнопку дает случайную другую карту. Нажатие на другую кнопку должно привести к анимации флип-карты, показывающей обратную сторону карты, или, если оборотная сторона уже показана, анимация флип-карты назад (та же карта). Чтобы получить анимацию флип-карты, анимируемый фрагмент должен находиться в контейнере, а не непосредственно в окне просмотра. Однако, когда я пытаюсь поместить контейнер фрагмента (также фрагмент) в пейджер, весь механизм страницы просмотра облажается. Обычное перелистывание больше невозможно.
Тот же / аналогичный вопрос задавался ранее: /questions/8383415/kak-ya-mogu-animirovat-fragment-v-okne-prosmotra, Принятый ответ не отвечает на мой вопрос, но показывает в комментариях, что больше людей ищут этот ответ.
Я много просматривал Интернет и продолжу, но я решил опубликовать свой вопрос здесь, потому что большинство ответов, которые я нашел на проблемы, пришли от вас, пользователей stackru!
Отредактировано, чтобы уточнить вопросы в комментариях. Анимация, которую я хочу использовать, работает с контейнером, как указано в:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:fitsSystemWindows="true"
tools:context="nl.xxx.xxx.xxxActivity"
tools:ignore="MergeRootFrame">
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
/>
</FrameLayout>
Перед анимацией фрагмент с imageView добавляется в контейнер (FrontFragment). Расположение этого фрагмента:
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/imageDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
tools:context="nl.xxx.xxx.xxxActivity" />
Анимация есть (часть кода:)
mShowingBack = true;
// Create and commit a new fragment transaction that adds the fragment for the back of
// the card, uses custom animations, and is part of the fragment manager's back stack.
BackFragment achterkant= BackFragment.newInstance("blabla");
getFragmentManager()
.beginTransaction()
// Replace the default fragment animations with animator resources representing
// rotations when switching to the back of the card, as well as animator
// resources representing rotations when flipping back to the front (e.g. when
// the system Back button is pressed).
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
// Replace any fragments currently in the container view with a fragment
.replace(R.id.container, achterkant)
// Add this transaction to the back stack, allowing users to press Back
// to get to the front of the card.
.addToBackStack(null)
// Commit the transaction.
.commit();
Анимации представлены в xml-файлах, например: card_flip_left_in.xml:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Before rotating, immediately set the alpha to 0. -->
<objectAnimator
android:valueFrom="1.0"
android:valueTo="0.0"
android:propertyName="alpha"
android:duration="0" />
<!-- Rotate. -->
<objectAnimator
android:valueFrom="-180"
android:valueTo="0"
android:propertyName="rotationY"
android:interpolator="@android:interpolator/accelerate_decelerate"
android:duration="@integer/card_flip_time_full" />
<!-- Half-way through the rotation (see startOffset), set the alpha to 1. -->
<objectAnimator
android:valueFrom="0.0"
android:valueTo="1.0"
android:propertyName="alpha"
android:startOffset="@integer/card_flip_time_half"
android:duration="1" />
Вышеприведенный код был продублирован из Интернета и отлично работает в ситуации отсутствия просмотра.
1 ответ
Я нашел ответ сам. Я добавил Rootfragment с контейнером в ViewPager. Я заменяю / анимирую фрагменты в контейнере с помощью getChildFragmentManager() и вышеупомянутых объектаниматоров.
Подсказка была в том, что мне пришлось использовать библиотеку android.support.v13 (FragmentStatePagerAdapter) в сочетании с android.app.Fragment и android.app.FragmentTransaction.