Android 渐变背景,颜色多变类似呼吸灯效果
本博是记录开发过程中用到的一个小知识点,小到怕忘了,还是在这里记录一下
主要是使用xml文件创建一个可以使背景渐变并变换颜色,使用的是AnimationList
首先创建几个渐变的背景drawable
<?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="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="#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="135"
android:endColor="#34e89e"
android:startColor="#0f3443"
/>
</shape>
创建完成这几个drawable资源后,需要使用一个AnimationList
<?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>
接下来在Activity的布局文件中,跟布局添加background为AnimationList xml文件即可
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rl"
android:background="@drawable/gradient_animation_list"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
</RelativeLayout>
最后在Activity中调用即可
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
AnimationDrawable background = (AnimationDrawable)rl.getBackground();
background.setEnterFadeDuration(2500);
background.setExitFadeDuration(5000);
background.start();
}
}
效果图如下: