Change Image Opacity Programmatically in Kotlin - RRutors
Last updated Dec 21, 2021In this article, we will see how to change the opacity of image programatically based on seekbar seek percentage in Android Studio by using Kotlin Language.
Opacity is the extent to which something blocks light. "Opacity" setting that allows you to adjust the transparency of an image. To understand opacity, it is important understand what "opaque" means. An opaque object is completely impervious to light, which means you cannot see through it.
SeekBar: The Android SeekBar is a ProgressBar with a movable thumb. The end user can move the progress of the song, file download, and so on by dragging the thumb left and right.
SeekBar has many attributes: thumbTint, progressTint, max, id, layout_margin etc....
ImageView: ImageView is a widget which is used to set or show the image in a particular frame by using its attribute (src).
Implementation:
Step 1. Create a new Project in android studio.
Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish |
Step 2. Go to activity_main.xml file and add the following code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <ImageView <SeekBar </LinearLayout> |
You will get the output from above xml code.
![]() |
Step 3. Open MainActivity.kt file and add the following code below setContentView(R.layout.activity_main).
val seekBar = findViewById(R.id.seekBar) seekBar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener{ override fun onStartTrackingTouch(p0: SeekBar?) { } override fun onStopTrackingTouch(p0: SeekBar?) { }) |
The SeekBar.OnSeekBarChangeListener interface provides methods to perform even handling for seek bar.
OnSeekBarChangeListener has three override methods :
- onProgressChanged() - When we slide the seekbar it provides us progress in percentage.
- onStartTrackingTouch() - It is used when we start click on seekbar.
- onStopTrackingTouch() - used when we removed click from seekbar return final progress.
For change and set the opacity on imageView, we used:
imageView.setAlpha(p1) |
Step 4. Run the app on emulator or real device, you will get the output as in Video.
OUTPUT:
![]() |
Complete Source Code of Opacity of Image Android Example:
activity_main.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <ImageView <SeekBar </LinearLayout> |
MainActivity.kt file
class OpacityActivity : AppCompatActivity() { seekBar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener{ override fun onStartTrackingTouch(p0: SeekBar?) { } override fun onStopTrackingTouch(p0: SeekBar?) { }) |
Conclusion: In this article we have covered how to change the opacity of image dynamically using seekbar in Android Studio by using Kotlin Language.
Article Contributed By :
|
|
|
|
1441 Views |