How to load an image from a URL into an ImageView in Kotlin Android
How to load an image from a URL into an ImageView in Kotlin Android.
Here's a step-by-step tutorial on how to load an image from a URL into an ImageView in Kotlin for Android.
Step 1: Add the necessary dependencies
First, you need to add the necessary dependencies to your project. Open your project's build.gradle file and add the following lines to the dependencies block:
implementation 'com.squareup.picasso:picasso:2.71828'
Step 2: Add the INTERNET permission
In order to access the internet and load images from a URL, you need to add the INTERNET permission to your app's AndroidManifest.xml file. Open the file and add the following line inside the manifest tag:
<uses-permission android:name="android.permission.INTERNET" />
Step 3: Define the ImageView in your layout file
Open the layout file where you want to display the image and add an ImageView element. For example, if you want to display the image in the activity's layout file (activity_main.xml), you can use the following code:
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
Step 4: Load the image using Picasso
In your Kotlin code, you can use the Picasso library to load the image from a URL into the ImageView. Open the Kotlin file for your activity (e.g., MainActivity.kt) and add the following code:
import com.squareup.picasso.Picasso
class MainActivity : AppCompatActivity() {
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView)
val imageUrl = "https://example.com/image.jpg"
Picasso.get()
.load(imageUrl)
.into(imageView)
}
}
In the code above, replace "https://example.com/image.jpg" with the actual URL of the image you want to load.
Step 5: Run the app and check the result
Build and run your app on an Android device or emulator. The image from the specified URL should be loaded into the ImageView you defined in your layout file.
That's it! You have successfully loaded an image from a URL into an ImageView using Kotlin in Android.