淡入淡出动画(也称为“叠化”)逐渐淡出一个 View 或 ViewGroup,同时淡入另一个。此动画适用于您希望在应用中切换内容或视图的情况。此处显示的淡入淡出动画使用 ViewPropertyAnimator,适用于 Android 3.1(API 级别 12)及更高版本。
以下是从进度指示器切换到某些文字内容的淡入淡出示例。
淡入淡出动画
创建视图
首先,您需要创建两个要淡入淡出的视图。以下示例创建了一个进度指示器和一个可滚动的文本视图:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView style="?android:textAppearanceMedium"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/lorem_ipsum"
android:padding="16dp" />
</ScrollView>
<ProgressBar android:id="@+id/loading_spinner"
style="?android:progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private int shortAnimationDuration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Initially hide the content view.
binding.content.setVisibility(View.GONE);
// Retrieve and cache the system's default "short" animation time.
shortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
crossfade();
}
private void crossfade() {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
// 将容器设置为透明
binding.content.setAlpha(0f);
// 可见
binding.content.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
// 给容器设置动画
binding.content.animate()
.alpha(1f)//透明度为1
.setDuration(shortAnimationDuration)//透明时间
.setListener(null);//无监听
// Animate the loading view to 0% opacity. After the animation ends,
// set its visibility to GONE as an optimization step (it won't
// participate in layout passes, etc.)
binding.loadingSpinner.animate()
.alpha(0f)//透明度为0
.setDuration(shortAnimationDuration)//透明时间
.setListener(new AnimatorListenerAdapter() {//设置监听
@Override
public void onAnimationEnd(Animator animation) {
// ycang
binding.loadingSpinner.setVisibility(View.GONE);
}
});
}
}