An ImgeView as the name suggests is used display images in Android Applications. In this article we will be discussing how to programmatically create an ImageView in Kotlin .
First step is to create a new Project in Android Studio. For this follow these steps:
- Click on File, then New and then New Project and give name whatever you like
- Then, select Kotlin language Support and click next button.
- Select minimum SDK, whatever you need.
- Select Empty activity and then click finish.
After doing this you will see some directories on the left hand side after your project/gradle is finished loading. It should look like this:
After that, we need to design our layout. For that we need to work with the XML file. Go to app > res > layout and paste the folllowing code:
Modify activity_main.xml file
We will be needing a image to be used in application. You can use the images that you like but the images need to be copied from our local computer path to app/res/drawable folder.
Create ImageView in MainActivity.kt file
Open app/src/main/java/yourPackageName/MainActivity.kt and do the following changes:
Create ImageView widget like this:
val imageView = ImageView(this) // setting height and width of imageview imageView.layoutParams = LinearLayout.LayoutParams(400, 400) imageView.x = 20F //setting margin from left imageView.y = 20F //setting margin from top
then add the widget in layout using this
//accessing our relative layout from activity_main.xml val layout = findViewById(R.id.layout) // Add ImageView to LinearLayout layout?.addView(imageView) //adding image to the layout
Run as Emulator:
- ImageView in Kotlin
- Dynamic CheckedTextView in Kotlin
- Dynamic RadioButton in Kotlin
- Dynamic Switch in Kotlin
- Dynamic SeekBar in Kotlin
- Dynamic RatingBar in Kotlin
- Dynamic ImageButton in Kotlin
- Dynamic AutoCompleteTextView in Kotlin
- Dynamic DatePicker in Kotlin
- Dynamic TimePicker in Kotlin
- Dynamic TextClock in Kotlin
- Dynamic Spinner in Kotlin
- Dynamic Chronometer in Kotlin
- Dynamic ProgressBar in Kotlin
- Dynamic ImageSwitcher in Kotlin
- Dynamic TextSwitcher in Kotlin
- Dynamic TextView in Kotlin
- Dynamic Button in Kotlin
- Dynamic ScrollView in Kotlin
- Dynamic RadioGroup in Kotlin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.