我试图通过加载动画来实现自定义 fragment 。相同的代码适用于 Activity,但不适用于 Fragment。
这是我的 fragment 布局代码:
<FrameLayout 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"
tools:context="pw.osin.musicexpert.fragments.BusyFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/fragment_animation_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:background="@drawable/vinyl" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:background="@color/colorPrimaryDark">
<TextView
android:id="@+id/fragment_animation_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:text="@string/message_data_is_loading"
android:textColor="@color/colorPrimaryYellow"
android:textSize="20dp"
android:textStyle="bold" />
</FrameLayout>
</LinearLayout>
我在 fragment 的 OnCreate 方法中调用的方法
private fun setAnimation() {
Log.i(TAG, "Установка анимации")
val drawable = AnimationUtils.loadAnimation(this.context, R.anim.rotate_anim)
mAnimationDescription?.setText(R.string.message_data_is_loading);
mAnimationImage?.startAnimation(drawable)
}
private fun initViewItems(view: View?) {
Log.i(TAG, "Поиск элементов View")
mAnimationDescription = view?.findView<TextView>(R.id.animation_description);
mAnimationImage = view?.findView<ImageView>(R.id.animation_logo);
}
我的旋转动画代码:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:startOffset="0"
android:toDegrees="360" />
</set>
这里我将动画 fragment 附加到 OnCreate 方法中的 Activity
private var mTransaction: FragmentTransaction? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
attachFragment()
}
private fun attachFragment() {
mTransaction = supportFragmentManager.beginTransaction()
mTransaction?.add(R.id.main_activity_container, BusyFragment.newInstance("Получаем дату"))
mTransaction?.commit()
}
我需要在哪里调用开始动画方法?
谢谢。
最佳答案
来自 onResume
的文档:
Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume of the containing Activity's lifecycle.
您希望在动画一开始就可见时运行动画,因此我建议在 fragment 的 onResume
中启动动画,或重写该 fragment 所附加到的 Activity 中的 onFragmentsResumed
方法。
关于java - Android:加载 fragment 时启动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523247/