欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 定時(shí)器實(shí)現(xiàn)圖片的變換

 更新時(shí)間:2017年08月12日 16:42:26   作者:孵化恐龍蛋  
這篇文章主要介紹了Android 定時(shí)器實(shí)現(xiàn)圖片的變換的相關(guān)資料,利用到定時(shí)器和handler,message的結(jié)合實(shí)現(xiàn)改功能,需要的朋友可以參考下

Android 定時(shí)器實(shí)現(xiàn)圖片的變換

在Android中,要讓每秒進(jìn)行一次ui更新,就需要利用到定時(shí)器和handler,message的結(jié)合,如果不使用handler就不能達(dá)到更新ui的效果,我的理解是handler中存在一個(gè)隊(duì)列問題,可以保證不產(chǎn)生阻塞。 

代碼如下: 

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(); 
  } 
} 


在這段代碼中有兩點(diǎn)需要注意: 

第一:在更新完圖片后,需要刷新整個(gè)布局,linearlayout.invalidate(); 

第二:在用完定時(shí)器timer后,要在Activity被干掉的同時(shí)銷毀定時(shí)器timer。

以上就是Android 定時(shí)器的應(yīng)用,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

最新評論