在做项目开发过程中,有HTTP网络耗时请求,为了良好的用户体验,肯定会出现一个加载框,之前用的是ProgressBar,通过控制Bar的显示和隐藏来体现加载的过程,但是出现了一个问题,当请求到数据到数据部署到控件上时,也有一个耗时(在低端手机上尽显),这时候就出现了Bar卡顿的现象,给用户造成卡的感觉,体验极其不好,所以就想到了用另外一种方式:加载帧动画。在发起请求时就开始帧动画,数据部署完就停止动画。

 当Activty启动时我会发情HTTP请求同时加载帧动画,加载帧动画也是一个耗时过程,如果不做处理,会出现动画停滞的现象,所以就得把动画的预装载和启动放到两个不同的方法中,在Activity中肯定是先执行OnCreate方法,所以在OnCreate中先预装载动画,在OnwindowsFocused方法中再启动动画,动画就顺利启动了。但是在开发过程中又遇到一个问题,我的项目首页是个TAbHost,初始化焦点都在ActMain上,比如第二个选项卡所对应的Act就不会执行OnWindowsFocus方法,当时让我很头疼,后来终于找到了解决的方法。一下就列出Act启动时同时启动帧动画的几种解决方案,我用的是3 和4,在不同情况下选用不同的启动方案。



帧动画:

第一种方式启动帧动画:(在Activity启动时会自动运行动画)

AnimationDrawable ad;
ImageView iv = (ImageView) findViewById(R.id.animation_view);
iv.setBackgroundResource(R.drawable.animation);
ad = (AnimationDrawable) iv.getBackground();
iv.getViewTreeObserver().addOnPreDrawListener(opdl);

//当一个视图树将要绘制时产生事件,可以添加一个其事件处理函数
 

OnPreDrawListener opdl=new OnPreDrawListener(){
      @Override
      public boolean onPreDraw() {
         ad.start();
         return true; //注意此行返回的值
      }
   };

第二种方式启动动画:(在Activity启动时会自动运行动画)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
        animationDrawable = (AnimationDrawable) image.getBackground();
        RunAnim runAnim=new RunAnim();
        runAnim.execute("");
 

class RunAnim extends AsyncTask<String, String, String>
{
        @Override
        protected String doInBackground(String... params)
        {
            if (!animationDrawable.isRunning())
            {
                animationDrawable.stop();
                animationDrawable.start();
            }
            return "";
        }
}

 

第三种方式启动动画:(在Activity启动时会自动运行动画)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
        animationDrawable = (AnimationDrawable) image.getBackground();
image.post(new Runnable()
 {
            @Override
            public void run()
            {
                animationDrawable.start();
            }
        });

 

第四种方式启动动画:(在Activity启动时会自动运行动画)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
        animationDrawable = (AnimationDrawable) image.getBackground();
 

@Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        animationDrawable.start();
        super.onWindowFocusChanged(hasFocus);
    }



 小小经验,拿出来分享下,望大侠们吐槽!