Android активность сцены перехода другой цели анимации - PullRequest
0 голосов
/ 01 апреля 2019

Рассмотрим этот вариант использования: на главном экране есть две кнопки, когда пользователь нажимает кнопку «Создать случайное число», генерируется случайное число и используется полноэкранное действие для отображения номера.Сгенерированное случайное число показывается после «Last Number Generated:» впоследствии.Я пытаюсь использовать ActivityOptions.makeSceneTransitionAnimation() для добавления анимации перехода активности.Поэтому, когда пользователь нажимает кнопку «Сгенерировать случайное число», полноэкранное действие расширяется.Но когда пользователь отклоняет действие на весь экран, я хочу использовать «Последнее сгенерированное число:» в качестве цели анимации.Однако я не нахожу способа сделать это с ActivityOptions.makeSceneTransitionAnimation ().Когда действие в полноэкранном режиме прекращается, целью анимации всегда будет исходный вид, запускающий анимацию.Есть ли хитрость для достижения поведения?Вот исходный код:

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<TextView>(R.id.generate).setOnClickListener {
            startActivity(Intent(this, FullScreenActivity::class.java).apply {
                val randomNum = Random().nextInt(100)
                putExtra(FullScreenActivity.KEY, randomNum)
                findViewById<TextView>(R.id.last_result).text = "Last Number Generated: $randomNum"
            }, ActivityOptionsCompat.makeSceneTransitionAnimation(
                this, findViewById<TextView>(R.id.generate), "random"
            ).toBundle())
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/last_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="18dp"
        android:textSize="18sp"
        android:transitionName="random"
        android:text="Last Number Generated:"
        android:background="@color/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/generate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="18dp"
        android:textSize="18sp"
        android:text="Generate Random Number"
        android:transitionName="random"
        android:background="@color/colorPrimary"
        android:layout_marginTop="20dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/last_result"/>

</android.support.constraint.ConstraintLayout>

FullScreenActivity.kt:

class FullScreenActivity : AppCompatActivity() {

    companion object {
        const val KEY = "KEY"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_full_screen)
        val randomNumber = intent.getIntExtra(KEY, 0)
        findViewById<TextView>(R.id.full_screen).text = randomNumber.toString()
    }
}

activity_full_screen.xml:

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/full_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="72sp"
    android:gravity="center"
    android:transitionName="random"
    android:background="@color/colorAccent"/>

enter image description here

1 Ответ

1 голос
/ 09 апреля 2019

Вы должны добавить R.id.generate и R.id.last_result в makeSceneTransitionAnimation как sharedElements с различными transitionName с.

        Pair<View, String> pair1 = new Pair<>(generate, "random");
        Pair<View, String> pair2 = new Pair<>(lastResult, "lastResult");
        Bundle bundle = ActivityOptionsCompat.
                          makeSceneTransitionAnimation(MainActivity.this, pair1, pair2)
                         .toBundle();
        startActivity(intent, bundle); 

Тогда в FullScreenActivity вы должны просто где-то изменить transitionName из R.id.full_screen с "random" на "lastResult" (так же, как transitionName из R.id.last_result). Я делаю это в onBackPressed методе:

    @Override
    public void onBackPressed() {
        textView.setTransitionName("lastResult");
        super.onBackPressed();
    }

Результат:

enter image description here

...