本啟動動畫主要是利用了布局中一張圖檔的拉伸、縮放、旋轉、漸變的混合而成的動态效果;主要分以下三步展開:
第一:建立一個app工程,并在布局RelativeLayout中添加一個ImageView 控制,寬度設定成滿屏,随意選擇自己喜歡的一張圖檔,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.startapp.SplashActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/imageViewId"
android:src="@drawable/r"
/>
</RelativeLayout>
第二:回到Activity中為其布局添加效果,AlphaAnimation(漸變)範圍為0到1,ScaleAnimation(縮放)範圍為0到1,RotateAnimation(旋轉)範圍0到360度;代碼如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
activity_splash = (RelativeLayout) findViewById(R.id.activity_splash);
//漸變
AlphaAnimation aa = new AlphaAnimation(0,1);
//aa.setDuration(500); //持續時間
aa.setFillAfter(true);
//拉伸 ScaleAnimation.RELATIVE_TO_SELF :相對于自身
ScaleAnimation sa = new ScaleAnimation(0,1,0,1,ScaleAnimation.RELATIVE_TO_SELF,0.5f,ScaleAnimation.RELATIVE_TO_SELF,0.5f);
//sa.setDuration(500);
sa.setFillAfter(true);
//旋轉
RotateAnimation ra = new RotateAnimation(0,360,RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF,0.5f);
// ra.setDuration(500);
ra.setFillAfter(true);
//添加動畫到集合,此集合是無序的,
AnimationSet as = new AnimationSet(false);
as.addAnimation(aa);
as.addAnimation(ra);
as.addAnimation(sa);
as.setDuration(2000);
activity_splash.startAnimation(as);
as.setAnimationListener(new myAnimationListener());
}
第三:為動畫添加監聽事件,當動畫執行完後回調函數,以便可以執行其他的操作;此案例使用Toast的方式做示範。代碼如下:
class myAnimationListener implements Animation.AnimationListener{
//動畫開始前回調此函數
@Override
public void onAnimationStart(Animation animation) {
}
//動畫結束後回調此函數
@Override
public void onAnimationEnd(Animation animation) {
Toast.makeText(SplashActivity.this,"動畫結束",Toast.LENGTH_SHORT).show();
}
@Override
public void onAnimationRepeat(Animation animation) {
}