Android 简单动画的制作以及遇到的问题

package wht.android.loading;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity{
    
    public AnimationDrawable frameAnimation;
    public TextView tv;
    public ImageView iv;
    
    public boolean flag = false;
    
    
    public Handler handler = new Handler(){
        
        public void handleMessage(Message msg){
            StopAnimation();
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.donghua);
        iv = (ImageView) findViewById(R.id.imgeView);
        iv.setBackgroundResource(R.anim.loading);
        frameAnimation =  (AnimationDrawable) iv.getBackground();
        
        frameAnimation.setOneShot(true); //为真的时候最后一针会停下
        
    }
    
    public void StopAnimation(){
        
        flag = true;
        System.out.println(flag);
        frameAnimation.stop();
        iv.setVisibility(View.GONE);
        tv = (TextView)findViewById(R.id.text);
        tv.setText("启动成功!");
        
    }
    
    public void onWindowFocusChanged(boolean hasFocus) {  
        
        super.onWindowFocusChanged(hasFocus);
        frameAnimation.start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Thread.sleep(2000); // 线程休眠时为什么主线程也不运行
                    
                    handler.sendMessage(Message.obtain());
                    
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            
        }).start();
        
    }
    
}

 其中在onCreate 中创建了线程然后sleep,出现了一个问题,那就是界面没有显示出来

 界面完全显示出来要等到 onWindowFoucosChanged时才可以

还有一点,界面只能在UI主线程中更改,所以,我们要去实现handler机制来进行通信。

关于animation的使用,还有一点就是xml的编写

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <item android:drawable="@drawable/loader_frame_1" android:duration="300" />
    <item android:drawable="@drawable/loader_frame_2" android:duration="300" />
    <item android:drawable="@drawable/loader_frame_3" android:duration="300" />
    <item android:drawable="@drawable/loader_frame_4" android:duration="300" />
    <item android:drawable="@drawable/loader_frame_5" android:duration="300" />
    <item android:drawable="@drawable/loader_frame_6" android:duration="300" />
   
    
</animation-list>

其中包括每一帧的图片,和持续的时间。

原文地址:https://www.cnblogs.com/zhanglanyun/p/2820411.html