SoFunction
Updated on 2025-03-11

How to load images using control ImageView on Android

ImageView is generally used to load images on Android. Here I will briefly record how to use this control.

The easiest way is to use the ImageView tag directly in xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >  
<ImageView
 android:
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:src="@drawable/welcome"
/>
</LinearLayout>

If you don't want to be in xml, you can also load it in the program. for example:

@Override
protected void onCreate(Bundle savedInstanceState) {
 (savedInstanceState);
 //setContentView(.activity_main);
  
 ImageView welcome = new ImageView(this);
 ();
 setContentView(welcome);
}

When building the ImageView object, a parameter is passed to indicate that it is associated with the current context. This Context is processed by the system and provides services such as resource parsing, access to databases and preferences. Because the Activity class inherits from Context, and because your HelloWorld class is a subclass of the Activity, it is also a Context. So you can pass this as your Context to ImageView reference.

How to load network image resources in Android ImageView, the code is also shared with you:

package ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
public class MainActivity extends Activity { 
  //Define a picture display control  private ImageView imageView; 
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    (savedInstanceState); 
    setContentView(); 
    //Picture resources    String url = "/orignal/89429f6dhb99b4903ebcf&amp;690"; 
    //Get available pictures    Bitmap bitmap = getHttpBitmap(url); 
    imageView = (ImageView)(); 
    //show    (bitmap); 
     
  } 
  /**
    * Get online picture resources
    * @param url
    * @return
    */ 
  public static Bitmap getHttpBitmap(String url){ 
    URL myFileURL; 
    Bitmap bitmap=null; 
    try{ 
      myFileURL = new URL(url); 
      //Get connection      HttpURLConnection conn=(HttpURLConnection)(); 
      //Set the timeout to 6000ms, (0); means there is no time limit      (6000); 
      //Connection settings to obtain data flow      (true); 
      //Not using cache      (false); 
      //This sentence is optional and has no effect      //(); 
      //Get data stream      InputStream is = (); 
      //Analysis to get the picture      bitmap = (is); 
      //Close the data flow      (); 
    }catch(Exception e){ 
      (); 
    } 
     
    return bitmap; 
     
  } 
} 

The above is the entire content of this article. I hope you can give you a reference and I hope you can support me more.