Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

runOnUiThread inside a View

Tags:

java

android

view

I'm making a custom ImageView . One of the methods is to load an image from a URL. And I want to retrieve the Bitmap in a Thread and load the bitmap in the UI thread.

How can I make a runOnUIThread() call for painting the bitmap?

Is there some kind of built in function? Or should I create a Handler in the constructor and use it for running runnables in the UI thread?

like image 342
Addev Avatar asked Jun 18 '12 15:06

Addev


2 Answers

Download the Image via AsyncTask and set to your view in its onPostExecute method

OR

From a separate image downloading thread use the post method of View which will always run its Runnable on UI-thread:

yourImageView.post(new Runnable() {
    @Override
    public void run() {
        // set the downloaded image here

    }
});
like image 95
waqaslam Avatar answered Sep 22 '22 21:09

waqaslam


You can do something like this:

 new Thread(new Runnable() {
   public void run() {
     final Bitmap bm = getBitmapFromURL(myStation.getStation().imageURL);
     ((Activity) context).runOnUiThread(new Runnable() {
       public void run() {
         icon.setImageBitmap(bm);
       }
     });
   }
 }).start();

This will work outside of an activity, like in a ListAdapter.

like image 34
IgorGanapolsky Avatar answered Sep 22 '22 21:09

IgorGanapolsky