Share
Explore

Lab: Android Kotlin app that updates an ImageView programmatically.

Lab: Android Kotlin app that demonstrates lifecycle events and updates an ImageView programmatically. This app will use viewBinding and Kotlin DSL for Gradle files.

1. First, create a new Android project in Android Studio: - Choose "Empty Views Activity" as the template - Name it "LifecycleDemoApp" - Set the minimum SDK to API 24 (Android 7.0) - Use Kotlin as the programming language
2. Update the project-level build.gradle.kts file:
```kotlin // build.gradle.kts (Project level) plugins { id("com.android.application") version "8.2.0" apply false id("org.jetbrains.kotlin.android") version "1.9.0" apply false } ```
3. Update the module-level build.gradle.kts file:
```kotlin // build.gradle.kts (Module level) plugins { id("com.android.application") id("org.jetbrains.kotlin.android") }
android { namespace = "com.example.lifecycledemoapp" compileSdk = 34
defaultConfig { applicationId = "com.example.lifecycledemoapp" minSdk = 24 targetSdk = 34 versionCode = 1 versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
buildTypes { release { isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } buildFeatures { viewBinding = true } }
dependencies { implementation("androidx.core:core-ktx:1.12.0") implementation("androidx.appcompat:appcompat:1.6.1") implementation("com.google.android.material:material:1.11.0") implementation("androidx.constraintlayout:constraintlayout:2.1.4") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") } ```
4. Update the AndroidManifest.xml file:
```xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.LifecycleDemoApp" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
</manifest> ```
5. Update the activity_main.xml layout file:
```xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
<TextView android:id="@+id/lifecycleTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Lifecycle Events:" app:layout_constraintBottom_toTopOf="@+id/imageView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<ImageView android:id="@+id/imageView" android:layout_width="200dp" android:layout_height="200dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:contentDescription="Demo Image" />
<Button android:id="@+id/changeImageButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Image" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout> ```
6. Update the MainActivity.kt file:
```kotlin package com.example.lifecycledemoapp
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.example.lifecycledemoapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private var isFirstImage = true
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root)
logAndUpdateUI("onCreate")
// Set initial image binding.imageView.setImageResource(R.drawable.image1)
binding.changeImageButton.setOnClickListener { changeImage() } }
private fun changeImage() { if (isFirstImage) { binding.imageView.setImageResource(R.drawable.image2) } else { binding.imageView.setImageResource(R.drawable.image1) } isFirstImage = !isFirstImage }
override fun onStart() { super.onStart() logAndUpdateUI("onStart") }
override fun onResume() { super.onResume() logAndUpdateUI("onResume") }
override fun onPause() { super.onPause() logAndUpdateUI("onPause") }
override fun onStop() { super.onStop() logAndUpdateUI("onStop") }
override fun onDestroy() { super.onDestroy() logAndUpdateUI("onDestroy") }
private fun logAndUpdateUI(event: String) { Log.d("LifecycleDemo", event) binding.lifecycleTextView.text = "${binding.lifecycleTextView.text}\n$event" } } ```
7. Add two images to the drawable folder: - Right-click on the `res/drawable` folder - Select "New" -> "Image Asset" - Create two images named `image1` and `image2`
megaphone

I'll provide step-by-step instructions on adding images to your Android project and making them accessible as image1 and image2 for use in your changeImage() function. Here's how to do it:

Prepare your images:
Have two image files ready on your computer. They should be in a format like PNG or JPG.
Name them "image1" and "image2" respectively.
Add images to the project:
In Android Studio, expand the "app" folder in the Project view.
Right-click on the "res" folder.
Select New > Android Resource Directory.
Set the Resource type to "drawable" and click OK.
Copy images to the drawable folder:
Locate your "image1" and "image2" files on your computer.
Drag and drop both files into the newly created "drawable" folder in Android Studio.
If prompted, choose to copy the files.
Rename files if necessary:
If your files weren't already named "image1" and "image2", right-click on each file in the drawable folder.
Select Refactor > Rename.
Rename them to "image1" and "image2" respectively.
Click "Refactor" when prompted.
Verify the images:
Expand the "drawable" folder in the Project view.
You should see both "image1" and "image2" listed.
Update your changeImage() function:
Open your MainActivity.kt file.
Locate the changeImage() function.
Ensure it looks like this:
kotlin
Copy
private fun changeImage() {
if (isFirstImage) {
binding.imageView.setImageResource(R.drawable.image2)
} else {
binding.imageView.setImageResource(R.drawable.image1)
}
isFirstImage = !isFirstImage
}
Verify the ImageView in your layout:
Open your activity_main.xml file.
Ensure you have an ImageView with the id "imageView":

<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="Demo Image" />
Set initial image in onCreate():
In MainActivity.kt, add this line in the onCreate() method:
kotlin
Copy
binding.imageView.setImageResource(R.drawable.image1)
Now your images are properly added to the project and accessible as R.drawable.image1 and R.drawable.image2. The changeImage() function will alternate between these two images when called.
Remember to call changeImage() when you want to switch the image, for example, in response to a button click:
kotlin
Copy
binding.changeImageButton.setOnClickListener {
changeImage()
}
This setup allows you to easily switch between the two images in your app.
Now, your app is ready to run. It will demonstrate lifecycle events by logging them and updating the UI. It also allows changing the image displayed in the ImageView when the button is clicked.

To run the app:
1. Connect an Android device or start an emulator
2. Click the "Run" button in Android Studio

The app will show the current lifecycle events and allow you to change the displayed image by clicking the "Change Image" button.
As you interact with the app (e.g., rotating the device, minimizing and reopening the app), you'll see the lifecycle events being logged and displayed on the screen.

This simple app demonstrates:
1. Lifecycle events
2. Using viewBinding
3. Displaying an image using an ImageView
4. Programmatically updating the picture shown in an ImageView
5. Using Kotlin DSL for Gradle files

.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.