Recently we have seen that Instagram has introduced an eye-catching color changing background of the login page in their iOS version of the application. The page’s background keeps changing colors like a gradient which looks really amazing. There are some libraries available on the internet which can create the same effect for you but in this blog, we will learn how this can be done without any libraries.
What we are going to do.
- Create some drawable files with different color gradients.
- Create another drawable with animation-list tag and add all the created gradient drawables as the items.
- Use the animation-list drawable as the background of the view.
- Start the animation in the onCreate method of the Activity of the fragment.
Let us see the steps in detail and with some code snippets.
1) Creating drawable files
Create some drawables files which contain gradients. For example:
-> gradient_1.xml
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="225" android:endColor="#044fab" android:startColor="#21d6d3" /> </shape> |
-> gradient_2.xml
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="45" android:endColor="#933c94" android:startColor="#517f95" /> </shape> |
2) Create an animation-list drawable
Create background.xml drawable inside it we will define the items and set the gradient_1 and gradient_2 files as drawables.
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/gradient_1" android:duration="4000" /> <item android:drawable="@drawable/gradient_2" android:duration="4000" /> </animation-list> |
3) Using animation-list drawable
You can use the background.xml as the background a view.
1 2 3 4 5 6 |
<LinearLayout android:id="@+id/main_container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/login_background_gradient" android:orientation="vertical"/> |
4) Start the animation
In your activity or fragment, you will have to start the animation and this can be done in your onCreate method.
1 2 3 4 5 |
LinearLayout your_Layout = (LinearLayout) findViewById(R.id.main_container); AnimationDrawable animationDrawable = (AnimationDrawable) your_Layout.getBackground(); animationDrawable.setEnterFadeDuration(4000); animationDrawable.setExitFadeDuration(4000); animationDrawable.start(); |
On starting the animation it will start the transition between the gradient and it looks really cool.
Thank you very much. This is Vedesh Kumar signing off.