Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Create animated refresh button in Android

  sonic0002        2012-11-02 11:51:41       36,001        3    

In Android, we can have drawings on a button, also we can put animated drawings on a button as well. Today we will show how to create an animated refresh button with an animated spinner on it.

We need to create an animated drawing first. Here we name it as progress.xml and put it in the res/drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spin_refresh" android:oneshot="false">
    <item android:drawable="@drawable/ic_action_refresh1" android:duration="400" />
    <item android:drawable="@drawable/ic_action_refresh2" android:duration="400" />
    <item android:drawable="@drawable/ic_action_refresh1" android:duration="400" />
    <item android:drawable="@drawable/ic_action_refresh2" android:duration="400" />
 </animation-list>

Here ic_action_refresh1 and ic_action_refresh2 are two spinner pictures in the same folder as the progress.xml file.

You can find the two refresh images here :
 

Next in the layout xml file, we can create a button component by putting following codes:

    <Button android:id="@+id/detail_refresh_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/refresh"
        android:gravity="center"
        android:drawableLeft="@drawable/progress"
    />

Then what you need to do is in your Activity class, you need to have the following codes to get the animated drawable on the button:

Button refreshBtn=(Button)findViewById(R.id.detail_refresh_btn);
refreshBtn.setOnClickListener(detailRefreshClickListener);

AnimationDrawable d=(AnimationDrawable)refreshBtn.getCompoundDrawables()[0];

Here getCompoundDrawables()[0] is mapping to the android:drawableLeft="@drawable/progress" in the layout xml above.      

Finally, when you call

d.start();

You will have the animated drawable animate now.

You can use d.start() and d.stop() to control the start and stop of animation.

Hope this will help those who want to create regresh button with an animated spinner on it.

ANDROID  ANIMATION  SPINNER  REFRESH BUTTON 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  3 COMMENTS


Roger [Reply]@ 2015-09-30 10:54:41

How can I download the images?

Pi Ke [Reply]@ 2015-09-30 23:16:10

You mean the two icons in this article? If yes, you have two options here:

  1. Get the image location from the source code. 
  2. Download it before the page is fully loaded. Since this page loads a JS which will disable the ability of download images. You have to download it before that JS is loaded.
Anonymous [Reply]@ 2016-07-06 05:40:17

What is mean by this?

detailRefreshClickListener