runOnUiThread inside a View

前端 未结 3 1875
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 01:06

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

相关标签:
3条回答
  • 2021-01-04 01:13

    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.

    0 讨论(0)
  • 2021-01-04 01:31

    Create a class that extends from AsyncTask. Pass the ImageView in the constructor. In the doInBackground method, download the image. In the postExecute method, set the image to the ImageView.

    0 讨论(0)
  • 2021-01-04 01:33

    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
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题