原文地址:http://thetechnocafe.com/make-a-moving-gradient-background-in-android/
這是一個關(guān)于如何在Android上制作移動漸變背景的快速教程。
為了實現(xiàn)這個,我們需要使用AnimationList,現(xiàn)在讓我們開始吧。
首先我們需要創(chuàng)建5個漸變的drawables,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="225"
android:endColor="#1a2980"
android:startColor="#26d0ce"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="45"
android:endColor="#614385"
android:startColor="#516395"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="135"
android:endColor="#1d2b64"
android:startColor="#f8cdda"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="45"
android:endColor="#ff512f"
android:startColor="#dd2476"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="135"
android:endColor="#34e89e"
android:startColor="#0f3443"/>
</shape>
然后再一個新的xml drawable文件中添加如下代碼,包含一個AnimationList用來改變background從一個漸變到另一個漸變,在AnimationList標(biāo)簽中,添加5個item。
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/gradient_blue"
android:duration="5000"/>
<item android:drawable="@drawable/gradient_red"
android:duration="5000"/>
<item android:drawable="@drawable/gradient_teal"
android:duration="5000"/>
<item android:drawable="@drawable/gradient_purple"
android:duration="5000"/>
<item android:drawable="@drawable/gradient_indigo"
android:duration="5000"/>
</animation-list>
現(xiàn)在將它作為背景設(shè)置到activity的根布局上,并且不要忘了給View/ViewGroup設(shè)置一個id,我們需要在java代碼中引用他。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:id="@+id/match_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_animation_list"
android:orientation="vertical">
<!--Content goes here-->
</LinearLayout>
現(xiàn)在我們需要做的就是在java代碼中告訴animation list開啟動畫,我們可以調(diào)用AnimationDrawable.start()方法,代碼如下:
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linear_layout);
AnimationDrawable animationDrawable = (AnimationDrawable)linearLayout.getBackground();
animationDrawable.setEnterFadeDuration(2500);
animationDrawable.setExitFadeDuration(5000);
animationDrawable.start();
可以看到,我們引用了將動畫列表作為背景的LinearLayout,然后我們從AnimationDrawable中獲取他的背景,然后我們設(shè)置進(jìn)入和退出動畫的持續(xù)時間,并啟動它。
