Android: changing Image with time interval

后端 未结 5 891
走了就别回头了
走了就别回头了 2020-12-05 21:20

I am using ImageDownloader class to get images from server and getting these images links using an ArrayList. After downloading the Image I am setting the Image

相关标签:
5条回答
  • 2020-12-05 21:55

    Set up your ImageView like this:

      <ImageView
            android:id="@+id/imgBackground"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="fitXY" />
    

    You can Use TimerTask to achieve this.

    // Declaration and Initialization :

    List<String> mImageUrl = new ArrayList<String>();
    private ImageLoader mImageLoader =  new ImageLoader(MainActivity.this);
    Timer timer = new Timer(); // changed
    int i = 0;
    

    // Put this code in your onCreate :

    timer.scheduleAtFixedRate(new TimerTask() {
    
                @Override
                public void run() {
                    if (i < mImageUrl.size()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                mImageLoader.DisplayImage(mImageUrl.get(i), img);
                                i++;
                            }
                        });
                    } else {
                        i = 0;
                    }
                }
            }, 0, 2000);
    

    The timer task will start in 0 seconds and it will change the background every 2 seconds. You can change this as like as you want. Its working fine. I have tested.

    You can read more about the timertask here.

    You can also cancel the timer with the help of timer.cancel() HIH.

    0 讨论(0)
  • 2020-12-05 21:58
        final ImagesSerialized item;
        final ImageView bgImage=(ImageView) findViewById(R.id.image);
         ArrayList<ImagesSerialized> list;
                control = (Controller) getApplicationContext();
                list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
    
                 for(int i=0; i<list.size(); i++)
                 {
     runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                           item = list.get(i);
    
                 downloader = new ImageDownloader();
                 downloader.download(item.imageurl(), bgImage)
    
                            }
                        });
                 }
    
    0 讨论(0)
  • Try this way hope this will help you for more improvement of your code...

    1. you need "Aquery(AndroidQuery)" jar from this reference : https://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.24.3.jar

    2.now add this jar on your project lib folder and add to build path or as library.

    3.now it's time for code using "Aquery(AndroidQuery)" to download images from server(here is my demo code you can modified as per your requirement).

    "activity_main.xml"

           <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
               <ImageView
                android:id="@+id/imgFromServer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"/>
               <ProgressBar
                android:id="@+id/pbrImageLoader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"/>
             </FrameLayout>
        </LinearLayout>
    

    "MyActivity.java" public class MyActivity extends Activity{

        private ImageView imgFromServer;
        private ProgressBar pbrImageLoader;
        private AQuery aQuery;
        private int currentIndex;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imgFromServer = (ImageView) findViewById(R.id.imgFromServer);
            pbrImageLoader = (ProgressBar) findViewById(R.id.pbrImageLoader);
            aQuery = new AQuery(this);
            currentIndex=0;
            final ArrayList<String> imageUrlListFromServer = new ArrayList<String>();
            imageUrlListFromServer.add("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
            imageUrlListFromServer.add("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
            imageUrlListFromServer.add("http://www.hdwallshub.com/files/submissions/cookie_monster_hd_wallpaper_1405239014.jpg");
            imageUrlListFromServer.add("http://images4.fanpop.com/image/photos/17200000/Tangled-offical-wallpapers-tangled-17286338-1680-1050.jpg");
            imageUrlListFromServer.add("http://wakpaper.com/large/Moons_wallpapers_4.jpg");
    
            final Timer timer = new Timer();
            downloadImagesFromServer(imageUrlListFromServer, 0, new ImageDownloadedListener() {
                @Override
                public void onDownloadFinish() {
                    timer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imgFromServer.setImageBitmap(aQuery.getCachedImage(imageUrlListFromServer.get(currentIndex)));
                                   if(currentIndex == imageUrlListFromServer.size()-1){
                                       currentIndex=0;
                                   }else{
                                       currentIndex++;
                                   }
                                }
                            });
                        }
                    },0,2000);
                }
            });
    
    
    
        }
    
        private void downloadImagesFromServer(final ArrayList<String> imageUrlList,final int index,final ImageDownloadedListener listener){
    
            aQuery.progress(pbrImageLoader).ajax(imageUrlList.get(index), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
                @Override
                public void callback(String url, Bitmap object, AjaxStatus status) {
                    super.callback(url, object, status);
                    if ((imageUrlList.size() - 1) == index) {
                        listener.onDownloadFinish();
                    } else {
                        downloadImagesFromServer(imageUrlList, index + 1, listener);
                    }
                }
            });
    
        }
    
        interface ImageDownloadedListener{
            public void onDownloadFinish();
        }
    
    
    }
    
    Note : "Aquery(AndroidQuery)" also cache images on local so it not get same images from  server if it already downloaded.
    
    0 讨论(0)
  • 2020-12-05 22:05

    I do not know about ImageLoader component but scheduling a timer on a view is quite easy in Android.(Without any additional Object)

    final ImageView bgImage=(ImageView) findViewById(R.id.image);
    
    ...
    
    new Runnable() {
        int updateInterval = 1000; //=one second
    
        @Override
        public void run() {
    
            // Any code which goes here will be executed every 'updateInterval'
            // change your background here            
    
            bgImage.postDelayed(this, updateInterval);
        }
    }.run();
    

    You can change this template as you wish, suppose I want to stop this timer, for this purpose I have to add a stop method to my runnable(This stop method acts synchronized and do not cause inconsistency in timer inner codes):

    Runnable myRunnable = new Runnable() {
        int updateInterval = 1000; //=one second
        boolean stop = false;
    
        public void stop() {
            this.stop = true;
        }    
    
        @Override
        public void run() {
    
            // Any code which goes here will be executed every 'updateInterval'
            // change your background here            
    
            if(!stop) {
                bgImage.postDelayed(this, updateInterval);
            }
        }
    }.run();
    

    Now I can stop it by myRunnable.stop();

    EDIT : You should iterate your array of URLs and pass one of them to your downloader. It can be accomplished by this snippet code:

    int arraySize = list.size();
    
    new Runnable() {
        int currentIndex = 0;
        int updateInterval = 1000; //=one second
    
        @Override
        public void run() {
    
            currentIndex += 1;
            if(currentIndex == arraySize){
                currentIndex = 0;
            }
    
            item = list.get(currentIndex);       
            downloader.download(item.imageurl(), bgImage);            
    
            bgImage.postDelayed(this, updateInterval);
        }
    }.run();
    
    0 讨论(0)
  • 2020-12-05 22:08

    try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ImageView;
    
    public class MainActivity extends AppCompatActivity {
    public ImageView iv;
    public static Integer[] mThumbIds = {
        R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
    int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    iv = (ImageView) findViewById(R.id.imageView);
    i=0;
    t.start();
    }
    Thread t = new Thread() {
    @Override
    public void run() {
        try {
            while (!isInterrupted()) {
                Thread.sleep(1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv.setImageResource(mThumbIds[i]);
                        i++;
                        if(i >= mThumbIds.length){
                            i = 0;
                        }}});}} 
        catch (InterruptedException e) {
        }}};
    
    }
    
    0 讨论(0)
提交回复
热议问题