gpt4 book ai didi

android - Android Kotlin-淡出 Activity 并设置持续时间

转载 作者:行者123 更新时间:2023-12-02 13:40:07 24 4
gpt4 key购买 nike

这是我到目前为止所拥有的:

class ChooseUpload : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_choose_upload)

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}

override fun onStop() {
overridePendingTransition(0, android.R.anim.fade_out)
super.onStop()
}
}
如您所见,我已经尝试过2次来设置淡出动画,但是它不起作用,它仍然会左右滑动。虽然淡入淡出。
那么,如何既使它们工作又设置动画的持续时间呢?我希望它很快
在开始 Activity 之前,我也尝试过这样做:
        val bundle = ActivityOptionsCompat.makeCustomAnimation(
this,
android.R.anim.fade_in, android.R.anim.fade_out
).toBundle()
startActivity(i, bundle)

最佳答案

为了触发ActivityOptionsCompat的退出动画,您必须在完成 Activity 时调用supportFinishAfterTransition(),而不是通常的finish()。以我的经验,除了覆盖待处理的动画之外,您还需要执行此操作。
确保在主题中设置了<item name="android:windowActivityTransitions">true</item>
您可以直接在动画.xml文件中设置持续时间。这是我的stay.xml的示例:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%"
android:toYDelta="0%" />
为了方便起见,我将此逻辑放入BaseActivity中:
abstract class BaseActivity: AppCompatActivity() {
private var transition: Transition? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
transition = intent.getParcelableExtra(TRANSITION_ANIMATION)
}

override fun finish() {
transition?.let { animation ->
transition = null //Prevent recursive loop
supportFinishAfterTransition().also { overridePendingTransition(Transition.stay, animation.exitId) }
} ?: run {
super.finish()
}
}

companion object {
const val TRANSITION_ANIMATION = "TRANSITION_ANIMATION"
}
}
fun Activity.startActivityWithAnimation(intent: Intent, transition: Transition) {
intent.putExtra(BaseActivity.TRANSITION_ANIMATION, transition as Parcelable)
startActivity(intent, ActivityOptionsCompat.makeCustomAnimation(this, transition.enterId, Transition.stay).toBundle())
}
@Parcelize
enum class Transition constructor(val enterId: Int, val exitId: Int) : Parcelable {
FADE(android.R.anim.fade_in, android.R.anim.fade_out);

companion object {
val stay: Int
get() = R.anim.stay
}
}

关于android - Android Kotlin-淡出 Activity 并设置持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64249053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com