这两天在用美团的时候,平时中没有注意的一个小细节,今天注意到了,就是在进入新页面还没有加载数据的时候,我们都可以看到一个小人像是在跑步,于是我非常好奇这个东西是怎么做的呢?于是乎我就把它的apk下载下来,然后解压之后,看到了 drawable-xxhdpi-v4 目录下有4张类似跑步的图片;发现原来它是用了 Android动画中的帧动画来实现的。下面我们也来实现一个这样子的效果吧。
第一步我们把这几张图片放到那个 drawable-xhdpi 中
图片素材第二步:我们在drawable 目录下新建一个 loading.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false"
>
<item android:drawable="@drawable/progress_loading_image_01" android:duration="80"/>
<item android:drawable="@drawable/progress_loading_image_02" android:duration="80"/>
<item android:drawable="@drawable/progress_loading_image_03" android:duration="80"/>
<item android:drawable="@drawable/progress_loading_image_04" android:duration="80"/>
</animation-list>
第三部:上传布局文件,放在res/layout 目录下,文件名位 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<ImageView
android:id="@+id/iv_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/loading"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dip"
android:textSize="18sp"
android:text="加载中。。。"
/>
</LinearLayout>
第四部:就在我们的Activity中开启帧动画来就可以了
package com.example.demo;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import com.example.progressbar.R;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
ImageView iv_loading = (ImageView) findViewById(R.id.iv_loading);
AnimationDrawable loadingDrawable = (AnimationDrawable) iv_loading.getDrawable();
loadingDrawable.start();
}
}
效果图(由于生成gif的软件不是很好,中间会有一个停顿的过程,但是实际的效果是没有这个的):