Use Handler, Timer + Timertask to implement simple image carousel,

Source: Internet
Author: User

Use Handler, Timer + Timertask to implement simple image carousel,

The layout file is only placed in a simple ImageView and will not be displayed.

Below is the Activity

1 package com. example. administrator. handlerthreadmessagedemo; 2 3 import android. app. activity; 4 import android. OS. bundle; 5 import android. OS. handler; 6 import android. OS. message; 7 import android. widget. imageView; 8 import android. widget. textView; 9 import java. util. timer; 10 11 12 public class MainActivity extends Activity {13 14 private int images [] = new int [] {R. drawable. image1, R. drawable. image2, R. drawable. image3}; // 15 16 private ImageView imageView; 17 private int index = 0; // calculate 18 private TextView textView; 19 private Timer timer = new Timer (); 20 private Timertask timertask; 21 22 23 24 @ Override25 protected void onCreate (Bundle savedInstanceState) {26 27 super. onCreate (savedInstanceState); 28 setContentView (R. layout. activity_main); 29 imageView = (ImageView) findViewById (R. id. imageView); 30 textView = (TextView) findViewById (R. id. title); 31 timertask = new Timertask (); // put it back to 32 Timer in timer. schedule (timertask,); // use Timer to send an empty message every one second 33} 34 35 private Handler mhandler = new Handler () {36 @ Override37 public void handleMessage (Message msg) {38 super. handleMessage (msg); 39 if (msg. what = 0x111) {40 index ++; 41 imageView. setBackgroundResource (images [index % 3]); 42} 43} 44}; 45 46 class Timertask extends java. util. timerTask {47 48 @ Override49 public void run () {50 mhandler. sendEmptyMessage (0x111); 51} 52} 53 54}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.