Android 定时器实现图片的变换

在Android中,要让每秒进行一次ui更新,就需要利用到定时器和handler,message的结合,如果不使用handler就不能达到更新ui的效果,我的理解是handler中存在一个队列问题,可以保证不产生阻塞。 

代码如下: 

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity
{
  private LinearLayout linearlayout;

  private ImageView main_imageview;

  private int i = 0;

  Timer timer = new Timer();

  private Handler handler = new Handler()
  {
    @Override
    public void handleMessage(Message msg)
    {

      Log.e("@@@", i + "");
      //index=msg.what;
      if (i > 6)
      {
        i = 0;
      }
      else
      {
        switch (i)
        {
        case 1:
          main_imageview.setImageResource(R.drawable.loader_frame_1);
          break;
        case 2:
          main_imageview.setImageResource(R.drawable.loader_frame_2);
          break;
        case 3:
          main_imageview.setImageResource(R.drawable.loader_frame_3);
          break;
        case 4:
          main_imageview.setImageResource(R.drawable.loader_frame_4);
          break;
        case 5:
          main_imageview.setImageResource(R.drawable.loader_frame_5);
          break;
        case 6:
          main_imageview.setImageResource(R.drawable.loader_frame_6);
          break;
        default:
          break;
        }
        linearlayout.invalidate();
      }
      super.handleMessage(msg);
    }
  };

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initView();
  }

  public void initView()
  {
    linearlayout = (LinearLayout) findViewById(R.id.background_main);
    main_imageview = (ImageView) findViewById(R.id.main_imageview);

    timer.scheduleAtFixedRate(new TimerTask()
    {
      @Override
      public void run()
      {
        // TODO Auto-generated method stub
        i++;
        Message mesasge = new Message();
        mesasge.what = i;
        handler.sendMessage(mesasge);
      }
    }, 0, 500);
  }

  @Override
  protected void onDestroy()
  {
    // TODO Auto-generated method stub
    timer.cancel();
    super.onDestroy();
  }
}


在这段代码中有两点需要注意: 

第一:在更新完图片后,需要刷新整个布局,linearlayout.invalidate(); 

第二:在用完定时器timer后,要在Activity被干掉的同时销毁定时器timer。

以上就是Android 定时器的应用,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

02-05 06:22