渐变动画(也叫消失)通常指渐渐的淡出某个UI组件,同时同步地淡入另一个。当App想切换内容或View的情况下,这种动画很有用。渐变简短不易察觉,同时又提供从一个界面到下一个之间流畅的转换。如果在需要转换的时候没有使用任何动画效果,这会使得转换看上去感到生硬而仓促。
- xml布局
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/click_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击按钮"
/>
<TextView
android:id="@+id/content"
style="?android:textAppearanceMedium"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="aaaaaaaaaaaaaaaaaaaaaa"
android:padding="16dp" />
<ProgressBar android:id="@+id/loading_spinner"
style="?android:progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
效果是点击按钮后,渐渐隐藏ProgressBar , 显示 TextView
public class MainActivity extends AppCompatActivity {
private View mContentView;
private View mLoadingView;
private int mShortAnimationDuration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = findViewById(R.id.content);
mLoadingView = findViewById(R.id.loading_spinner);
mContentView.setVisibility(View.GONE);
// Retrieve and cache the system's default "short" animation time.
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
findViewById(R.id.click_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//渐变动画
crossfade();
}
});
}
private void crossfade() {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
mContentView.setAlpha(0f);
mContentView.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
mContentView.animate()
.alpha(1f)
.setDuration(2000)
.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.)
mLoadingView.animate()
.alpha(0f)
.setDuration(2000)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoadingView.setVisibility(View.GONE);
}
});
}